Resolved conflict after merging with master
diff --git a/erpnext/patches/__init__.py b/erpnext/patches/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/patches/__init__.py
diff --git a/erpnext/patches/delivery_billing_status_patch.py b/erpnext/patches/delivery_billing_status_patch.py
new file mode 100644
index 0000000..1fcd8bf
--- /dev/null
+++ b/erpnext/patches/delivery_billing_status_patch.py
@@ -0,0 +1,55 @@
+import webnotes
+sql = webnotes.conn.sql
+
+test=1
+
+# Update SO and DN Detail 
+#--------------------------
+def update_delivered_billed_qty():
+	# update billed amt in item table in so and dn
+	sql("""	update `tabSales Order Detail` so
+		set billed_amt = (select sum(amount) from `tabRV Detail` where `so_detail`= so.name and docstatus=1 and parent not like 'old%%'),
+		delivered_qty = (select sum(qty) from `tabDelivery Note Detail` where `prevdoc_detail_docname`= so.name and docstatus=1 and parent not like 'old%%'), 
+		modified = now()
+		where docstatus = 1
+	""")
+
+	sql(""" update `tabDelivery Note Detail` dn
+		set billed_amt = (select sum(amount) from `tabRV Detail` where `dn_detail`= dn.name and docstatus=1 and parent not like 'old%%'), 
+		modified = now()
+		where docstatus = 1
+	""")
+
+# update SO
+#---------------
+def update_percent():
+	# calculate % billed based on item table
+	sql("""	update `tabSales Order` so
+		set per_delivered = (select sum(if(qty > ifnull(delivered_qty, 0), delivered_qty, qty))/sum(qty)*100 from `tabSales Order Detail` where parent=so.name), 
+		per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabSales Order Detail` where parent = so.name), 
+		modified = now()
+		where docstatus = 1
+	""")
+		
+	# update DN	
+	# ---------	
+	sql("""	update `tabDelivery Note` dn
+		set per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabDelivery Note Detail` where parent = dn.name), 
+		modified = now()
+		where docstatus=1
+	""")
+
+# update delivery/billing status 
+#-------------------------------
+def update_status():
+	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'))""")
+			
+def run_patch():
+	update_delivered_billed_qty()
+	update_percent()
+	update_status()
diff --git a/erpnext/patches/erpnext_structure_cleanup.py b/erpnext/patches/erpnext_structure_cleanup.py
new file mode 100644
index 0000000..e78a82e
--- /dev/null
+++ b/erpnext/patches/erpnext_structure_cleanup.py
@@ -0,0 +1,200 @@
+#Cleanup all unwanted documents and restructure of moduloes
+#----------------------------------------------------------
+
+import webnotes
+from webnotes.model import delete_doc
+from webnotes.modules.module_manager import reload_doc
+from webnotes.modules.export_module import export_to_files
+sql = webnotes.conn.sql
+
+
+#----------------------------
+
+def delete_unwanted_doctypes():
+	"deletes doctypes which are not used anymore"
+	
+	try:
+		sql("delete from `tabMenu Item`")
+		sql("delete from tabDocField where fieldname = 'site_map_details' and parent ='Control Panel'")
+	except:
+		pass
+		
+	lst = ['Zone',  'WN Account Control', 'Wiki Page', 'Wiki History', 'Wiki Control', 'While You Were Out', 'Web Visitor', 'Tweet', 'Transfer Utility', 'Transfer Module', 'Transfer Control', 'Transfer Account', 'Tips Common', 'TestTabDT', 'TestDT', 'Test Type', 'Test Run', 'Test Record Detail', 'Test Record', 'Test Case', 'Supplier TDS Category Detail', 'Shopping Cart Control', 'Service Series', 'Series Detail', 'Rule Engine', 'RFQ', 'Report Filter Detail', 'Report Field Detail','Report Control', 'Rating Widget Record', 'Rating Widget Control', 'Rating Template Detail', 'Rating Template', 'PV Ded Tax Detail', 'PV Add Tax Detail', 'Product Variant', 'Product Variance', 'Product Group', 'Product Feature', 'Payroll Tips Common', 'Payroll Rule', 'Password Control', 'Page Visit', 'Patch', 'Multiple Transfer', 'Module Tip Control', 'Module Setter', 'Module Manager', 'Module Import', 'Module Detail', 'Message Control', 'Message', 'Mail Participant Details', 'Mail', 'Leave Type Detail', 'Leave Detail', 'Leave Applicable Detail', 'Lead Item Detail', 'Lead Attachment Detail', 'Item Attachments Detail', 'Instant Message', 'Impact Analysis', 'Forum Topic', 'Forum Control', 'Form Settings', 'Follower', 'ERP Setup', 'Enquiry Attachment Detail', 'Documentation', 'Condition Detail', 'Complaint Note', 'Code History', 'Code Editor', 'Code Backup Control', 'Code Backup', 'City', 'Change Log', 'Business Letter Type', 'Business Letter Template', 'Business Letter', 'Badge Settings Detail', 'Application Type', 'Application', 'Action Detail', 'Accounts Setup', 'Stock Common', 'Job Application', 'Service Schedule', 'Comment Control', 'Bank', 'Tag Widget Control', 'Feature Update', 'RFQ Detail', 'Supplier Quotation Detail', 'Supplier Quotation', 'Year Closing Voucher', 'Approval Structure', 'Site Map Detail', 'Menu Control', 'Menu Item', 'Menu Item Role'] # bank
+	for d in lst:
+		try:
+			sql("delete from `tabProperty Setter` where select_doctype = '%s'" % d)
+			sql("delete from `tabCustom Script` where dt = '%s'" % d)
+			sql("delete from `tabCustom Field` where dt = '%s'" % d)
+			delete_doc('DocType', d)
+		except:
+			pass
+	
+		
+	sql("commit")	
+	delete_tables(lst)
+		
+def delete_tables(lst):
+	for d in lst:
+		for t in ['tab', 'arc']:
+			try:
+				sql("drop table `%s%s`" % (t, d))
+			except:
+				continue
+	
+def delete_unwanted_pages():
+	"deletes pages which are not used anymore"
+	lst = ['Transaction Authorization', 'Prduct Display', 'Data Import', 'Partner Home', 'Product Display', 'Module Settings', 'About Us', 'Custom Reports', 'MIS', 'MIS - Comparison Report', 'Monthly MIS', 'MyReports', 'Navigation Page', 'Point Race', 'Tag Widget', 'Widget Test', 'Yearly MIS']
+	for d in lst:
+		try:
+			delete_doc('Page', d)
+		except:
+			pass
+			
+			
+def delete_unwanted_search_criteria():
+	"deletes search criteria which are not used anymore"
+	
+	sql("update `tabSearch Criteria` set module = 'HR' where name = 'salary_structure_details'")
+	
+	lst = ['_SRCH00002', '_SRCH00001', 'warranty-amc_summary1', 'test_so4', 'test_so3', 'test_so2', 'test_so1', 'test_so', 'test5', 'target_variance_report1', 'STDSRCH/00006', 'STDSRCH/00005', 'STDSRCH/00004', 'STDSRCH/00003', 'STDSRCH/00002', 'STDSRCH/00001', 'so_pending_items_6', 'so_pending_items_5', 'so_pending_items_3', 'so_pending_items_34', 'scrap', 'sales_report_test', 'salary_structure_details1', 'salary_structure_details2', 'salary_structure_details3', 'salary_slips1', 'projectwise_pending_qty_and_costs2', 'projectwise_pending_qty_and_costs1', 'projectwise_delivered_qty_and_costs1', 'projectwise_delivered_qty_and_costs2', 'New Search Criteria 1', 'monthly_salary_register2', 'monthly_salary_register1', 'installed_items','follow_up_history', 'follow_up_report', 'employee_in_company_experience2', 'employee_in_company_experience1', 'employee_in_company_experience', 'employee_details', 'employee_details1', 'employee_details2', 'employees_birthday1', 'draft_so_pending_items', 'draft_sales_orders', 'delivery_notewise_pending_qty_to_install', 'datewise_leave_report2', 'datewise_leave_report1', 'datewise_leave_report', 'customer_issues1', 'cancelled_so_pending_items1', 'cancelled_so_pending_items', 'budget_variance_report3', 'budget_variance_report1', 'account_-_inputs_rg_23_a_-_part_ii_wrong_one', 'territory_item_group_wise_gp', 'sales_orderwise_pending_packing_item_summary', 'itemwise_trend', 'monthly_attendance_details_old', 'projectwise_contribution_report', 'projectwise_delivery_and_material_cost', 'projectwise_delivery_and_mat_cost_report', 'territorywise_trend', 'test_dn', 'rfq', 'rfq1']
+	
+	for d in lst:
+		if sql("select name from `tabSearch Criteria` where ifnull(standard, 'Yes') = 'Yes' and name = '%s'" % d):
+			try:
+				delete_doc('Search Criteria', d)
+			except:
+				pass
+		
+	
+def delete_unwanted_mappers():
+	"deletes unwanted mappers"
+	
+	lst = ['Customer Issue-Maintenance Report', 'Enquiry-Service Quotation', 'Sales Order-Maintenance Report', 'Service Quotation-Service Order', 'Supplier Quotation-Purchase Order', 'Visit Schedule-Maintenance Report', 'RFQ-Supplier Quotation', 'Indent-RFQ']
+	for d in lst:
+		try:
+			delete_doc('DocType Mapper', d)
+		except:
+			pass	
+			
+def delete_unwanted_modules():
+	"deletes unwanted modules"
+	lst = ['Development', 'Recycle Bin', 'Testing', 'Testing System', 'Test', 'Partner Updates', 'My Company', 'Event Updates', 'E-Commerce']
+	for d in lst:
+		try:
+			delete_doc('Module Def', d)
+		except:
+			pass
+
+#---------------------------------------------	
+
+def rename_merge_modules():
+	"Rename module as per users view and merge for removing confusion"
+	
+	rename_lst = [['CRM', 'Selling'], ['SRM','Buying'], ['Material Management', 'Stock'], ['Payroll','HR'], ['Maintenance', 'Support']]
+	for d in rename_lst:
+		# create new module manually and export to file???????
+		reload_doc(d[1].lower(), 'Module Def', d[1])
+
+	merge_lst = [['Tools', 'Utilities'], ['Application Internal', 'Utilities'], ['Settings', 'Setup']]
+	# settings hardcoded in my_company
+	# module hardcoded in home_control
+	# material_management hardcoded in installation note
+	# maintenance hardcoded in support_email_settings
+	
+	lst = rename_lst + merge_lst
+	for d in lst:
+		update_module(d[0], d[1])
+		try:
+			delete_doc('Module Def', d[0])
+		except:
+			pass
+	reload_doc('Utilities', 'Module Def', 'Utilities')
+	
+def update_module(from_mod, to_mod):
+	for t in ['DocType', 'Page', 'Search Criteria', 'DocType Mapper', 'Print Format', 'Role']:
+		sql("update `tab%s` set module='%s' where module = '%s'"% (t, to_mod, from_mod))
+		
+#------------------------------------ 
+def sync_roles():
+	"Put Roles into corresponding module and delete Roles module"
+	
+	# roles
+	roles = {
+		'Accounts'	:		"'Accounts Manager', 'Accounts User', 'Auditor'", 
+		'Selling'	: 		"'Customer', 'Sales User', 'Sales Manager', 'Sales Master Manager', 'Partner'", 
+		'Buying'	:		"'Supplier', 'Purchase User', 'Purchase Manager', 'Purchase Master Manager'", 
+		'Stock'		:		"'Material User', 'Material Master Manager', 'Material Manager', 'Quality Manager'", 
+		'Support'	:		"'Support Team', 'Support Manager', 'Maintenance User', 'Maintenance Manager'", 
+		'Production':		"'Production User', 'Production Manager', 'Production Master Manager'", 
+		'Setup'		:		"'System Manager'", 
+		'Projects'	:		"'Projects User'", 
+		'HR'		:		"'HR User', 'HR Manager', 'Employee'",
+		'Core'		:		"'Administrator', 'All', 'Guest'"
+	}
+	for mod in roles.keys():
+		sql("update `tabRole` set module = '%s' where name in (%s)" % (mod, roles[mod]))
+		
+	sql("update `tabDocType` set module = 'Setup' where name = 'Role'")
+	try:
+	
+		delete_doc('Module Def', 'Roles')
+	except:
+		pass
+#------------------------------------ 
+def sync_mapper():
+	"Put mappers into corresponding module"
+		
+	mappers = {
+		'Accounts':		('Delivery Note-Receivable Voucher', 'Project-Receivable Voucher', 'Purchase Order-Payable Voucher', 'Purchase Receipt-Payable Voucher', 'Sales Order-Receivable Voucher'), 
+		'Selling': 		('Delivery Note-Installation Note', 'Enquiry-Quotation', 'Lead-Enquiry', 'Lead-Customer', 'Project-Sales Order', 'Quotation-Sales Order', ), 
+		'Buying':		('Indent-Purchase Order', 'Sales Order-Indent'), 
+		'Stock':		('Purchase Order-Purchase Receipt', 'Project-Delivery Note', 'Receivable Voucher-Delivery Note', 'Sales Order-Delivery Note'), 
+		'Support':		('Customer Issue-Maintenance Visit', 'Sales Order-Maintenance Schedule', 'Sales Order-Maintenance Visit'), 
+		'Production':	('Production Forecast-Production Plan', 'Production Forecast-Production Planning Tool', 'Sales Order-Production Plan'), 
+		'HR':			('KRA Template-Appraisal', 'Salary Structure-Salary Slip')
+	}
+	
+	for mod in mappers.keys():
+		sql("update `tabDocType Mapper` set module = '%s' where name in %s" % (mod, mappers[mod]))
+	try:
+		delete_doc('Module Def', 'Mapper')
+	except:
+		pass
+# --------------------------------------
+# function below will be run only in localhost
+'''def export_docs():
+	"""
+		Export all documents where module has been changed
+	"""
+	for dtype in ['DocType', 'Page', 'Search Criteria', 'DocType Mapper', 'Print Format', 'Role']:
+		lst = sql("select name, module from `tab%s`" % dtype)
+		for rec in lst:
+			webnotes.msgprint(rec)
+			if rec and rec[0] and rec[1]:
+				export_to_files(record_list = [[dtype, rec[0]]], record_module = rec[1])
+
+	#grep test company
+'''
+
+#---------------------------------------
+def run_patches():
+	# update module
+	dt_module = {'LC PR Detail':'Stock', 'Landed Cost Detail':'Stock', 'Comment Widget Record': 'Core', 'Tag':'Core', 'Tag Detail': 'Core', 'POS Settings': 'Accounts', 'Menu Item': 'Setup', 'Menu Item Role': 'Setup'}
+	for d in dt_module.keys():
+		sql("update `tabDocType` set module = '%s' where name = '%s'" % (dt_module[d], d))
+	delete_unwanted_mappers()
+	delete_unwanted_doctypes()
+	sql("start transaction")
+	delete_unwanted_pages()
+
+	delete_unwanted_search_criteria()
+
+	
+	rename_merge_modules()
+	sync_roles()
+	sync_mapper()
+	delete_unwanted_modules()
+	# landed cost wizard link in stock
+	reload_doc('stock', 'Module Def', 'Stock')
+	
+	sql("commit")
diff --git a/erpnext/patches/index_patch.py b/erpnext/patches/index_patch.py
new file mode 100644
index 0000000..3ef8ec3
--- /dev/null
+++ b/erpnext/patches/index_patch.py
@@ -0,0 +1,295 @@
+"""
+	This patch removes wrong indexs and add proper indexes in tables
+"""
+
+import webnotes
+sql = webnotes.conn.sql
+from webnotes.utils import cint, cstr
+
+def create_proper_index():
+	from webnotes.modules.export_module import export_to_files
+
+	dt_index_fields={
+						'Purchase Receipt Detail': ['prevdoc_docname', 'item_code', 'warehouse', 'prevdoc_detail_docname'], 
+						'Period Closing Voucher': ['closing_account_head', 'fiscal_year'], 
+						'Lead': ['lead_name', 'status', 'transaction_date'], 
+						'Time Sheet Detail': ['app_name'], 
+						'Item Specification Detail': [], 
+						'Budget Detail': ['fiscal_year', 'account'], 
+						'Grade': [], 
+						'RV Tax Detail': ['parenttype', 'account_head'], 
+						'TDS Category Account': ['account_head'], 
+						'Role': [], 
+						'Leave Allocation': ['leave_type', 'employee', 'fiscal_year'], 
+						'Branch': [], 
+						'Department': [], 
+						'Contact Detail': [], 
+						'Territory': ['lft', 'rgt', 'parent_territory'], 
+						'Item Tax': ['tax_type'], 
+						'Bin': ['warehouse', 'item_code'], 
+						'PPW Detail': ['warehouse'], 
+						'Sales Partner': ['partner_name'], 
+						'Default Home Page': ['home_page', 'role'], 
+						'Custom Field': ['dt'], 
+						'DocFormat': ['format'], 
+						'DocType Mapper': ['from_doctype', 'to_doctype'], 
+						'Brand': [], 
+						'Order Lost Reason': [], 
+						'Journal Voucher': ['posting_date', 'voucher_type'], 
+						'TDS Return Acknowledgement': ['date_of_receipt', 'acknowledgement'], 
+						'BOM Report Detail': ['item_code'], 
+						'Quotation Detail': ['item_code'], 
+						'Update Delivery Date Detail': ['sales_order_no'], 
+						'Advance Adjustment Detail': ['journal_voucher'], 
+						'Authorization Rule': ['approving_user', 'system_user', 'system_role', 'approving_role'], 
+						'DocPerm': ['permlevel', 'role'], 
+						'Stock Entry Detail': ['item_code', 't_warehouse', 's_warehouse'], 
+						'Stock Entry': ['posting_date', 'delivery_note_no', 'purchase_receipt_no', 'production_order'], 
+						'Price List': [], 
+						'KRA Sheet': [], 
+						'Production Order': ['status', 'project_name', 'production_item'], 
+						'Account': ['lft', 'rgt', 'parent_account'], 
+						'Earn Deduction Detail': [], 
+						'Indent': ['status', 'transaction_date'], 
+						'Tag Detail': [], 
+						'SS Deduction Detail': ['d_type'], 
+						'Batch': ['item'], 
+						'Deduction Type': [], 
+						'Project': ['project_name', 'customer'], 
+						'UserRole': ['role'], 
+						'DocField': ['label', 'fieldtype', 'fieldname'], 
+						'Property Setter': ['doc_type', 'doc_name', 'property'], 
+						'Appraisal': ['status', 'employee'], 
+						'Letter Head': [], 
+						'Follow up': ['follow_up_by'], 
+						'Project Cost Breakup': [], 
+						'Table Mapper Detail': [], 
+						'Campaign': [], 
+						'Static Parameter Detail': [], 
+						'Leave Type': [], 
+						'Account Balance': ['period', 'start_date', 'end_date', 'account'], 
+						'Absent Days Detail': [], 
+						'Tag': [], 
+						'Raw Materials Supplied': ['raw_material'], 
+						'Project Activity Update': [], 
+						'PR Raw Material Detail': [], 
+						'Bank Reconciliation Detail': ['voucher_id'], 
+						'Sales Order': ['quotation_no', 'project_name', 'customer', 'posting_date'], 
+						'Chapter VI A Detail': [], 
+						'Experience In Company Detail': [], 
+						'Order Reconciliation Detail': ['sales_order_no'], 
+						'Attendance': ['employee', 'att_date'], 
+						'Previous Experience Detail': [], 
+						'Earning Detail': ['e_type'], 
+						'Sales Order Detail': ['item_code', 'prevdoc_docname', 'reserved_warehouse'], 
+						'KRA Template': [], 
+						'Budget Distribution': ['fiscal_year'], 
+						'Workstation': ['warehouse'], 
+						'Period': [], 
+						'Training Session Details': [], 
+						'Other Charges': [], 
+						'State': [], 
+						'Bulk Rename Tool': [], 
+						'Landed Cost Master Detail': [], 
+						'Employee': ['employee_name', 'designation', 'department'], 
+						'Terms And Conditions': [], 
+						'TC Detail': [], 
+						'UOM': [], 
+						'Supplier Type': [], 
+						'Project Milestone': [], 
+						'Landed Cost Master': [], 
+						'Budget Distribution Detail': [], 
+						'Form 16A Ack Detail': [], 
+						'Campaign Expense': [], 
+						'Time Sheet': ['employee_name', 'time_sheet_date'], 
+						'File Group': ['parent_group'], 
+						'Maintenance Visit Detail': ['item_code', 'service_person'], 
+						'Support Ticket Response': [], 
+						'PV Detail': ['item_code', 'purchase_order', 'po_detail', 'purchase_receipt', 'pr_detail', 'expense_head', 'cost_center'], 
+						'Timesheet Detail': ['project_name', 'task_id', 'customer_name'], 
+						'Holiday List Detail': [], 
+						'Workflow Rule Detail': [], 
+						'Module Def': ['module_seq', 'module_page'], 
+						'Term': [], 
+						'PF Detail': ['item_code'], 
+						'POS Setting': ['user', 'territory'], 
+						'QA Specification Detail': [], 
+						'Support Ticket': ['customer', 'allocated_to', 'status'], 
+						'Project Activity': ['project'], 
+						'Customer Group': ['lft', 'rgt', 'parent_customer_group'], 
+						'Return Detail': ['item_code'], 
+						'Series Detail': [], 
+						'Event Role': ['role'], 
+						'Contact': ['employee_id'], 
+						'BOM Material': ['item_code', 'bom_no'], 
+						'Invest 80 Declaration Detail': [], 
+						'PO Raw Material Detail': [], 
+						'Industry Type': [], 
+						'Declaration Detail': [], 
+						'Holiday List': ['fiscal_year'], 
+						'Sales Person': ['lft', 'rgt', 'parent_sales_person'], 
+						'RV Detail': ['item_code', 'sales_order', 'so_detail', 'delivery_note', 'dn_detail', 'cost_center', 'income_account'], 
+						'Module Def Item': [], 
+						'TDS Category': [], 
+						'DocTrigger': [], 
+						'Print Format': ['standard'], 
+						'Installed Item Details': ['prevdoc_docname', 'item_code'], 
+						'Form 16A Tax Detail': [], 
+						'Event': ['event_date', 'event_type'], 
+						'Currency': [], 
+						'Service Quotation Detail': ['item_code'], 
+						'Warehouse Type': ['warehouse_type'], 
+						'Sales BOM': ['item_group'], 
+						'IT Checklist': ['employee'], 
+						'Purchase Other Charges': [], 
+						'Company': [], 
+						'Call Log': [], 
+						'Professional Training Details': [], 
+						'Warehouse': ['warehouse_type'], 
+						'Competitor': [], 
+						'Mode of Payment': [], 
+						'Training Session': ['customer'], 
+						'Cost Center': ['lft', 'rgt', 'parent_cost_center'], 
+						'Timesheet': ['status', 'timesheet_date'], 
+						'Form 16A': ['party_no'], 
+						'Sales BOM Detail': ['item_code'], 
+						'Answer': ['question'], 
+						'Supplier': [], 
+						'Installation Note': ['delivery_note_no', 'customer', 'inst_date'], 
+						'Expense Voucher': ['approval_status', 'employee'], 
+						'Target Detail': ['from_date', 'to_date', 'fiscal_year'], 
+						'Page Role': ['role'], 
+						'Partner Target Detail': ['fiscal_year', 'item_group'], 
+						'Shipping Address': ['customer'], 
+						'Indent Detail': ['item_code', 'warehouse'], 
+						'TDS Payment Detail': [], 
+						'Market Segment': [], 
+						'Comment Widget Record': [], 
+						'Service Order Detail': ['item_code', 'prevdoc_docname'], 
+						'TDS Payment': ['from_date', 'to_date', 'tds_category'], 
+						'Lead Email CC Detail': [], 
+						'User Setting-Role User': [], 
+						'Salary Slip': ['month', 'year', 'employee'], 
+						'Maintenance Schedule Detail': ['item_code', 'scheduled_date'], 
+						'Employment Type': [], 
+						'Advance Allocation Detail': ['journal_voucher'], 
+						'Quotation': ['customer', 'transaction_date'], 
+						'Deduction Detail': ['d_type'], 
+						'Bill Of Materials': ['item', 'project_name'], 
+						'Earning Type': [], 
+						'Designation': [], 
+						'BOM Replace Utility Detail': ['parent_bom'], 
+						'Question': [], 
+						'Stock Ledger Entry': ['item_code', 'warehouse', 'posting_date', 'posting_time'], 
+						'Educational Qualifications Detail': [], 
+						'BOM Operation': [], 
+						'Item Group': ['lft', 'rgt', 'parent_item_group'], 
+						'Workflow Action Detail': [], 
+						'User Setting-Profile': [], 
+						'Customer Issue': ['item_code', 'customer', 'complaint_date'], 
+						'Feed': [], 
+						'Purchase Tax Detail': ['account_head'], 
+						'GL Mapper Detail': [], 
+						'TDS Detail': [], 
+						'PRO Detail': ['item_code', 'source_warehouse'], 
+						'DocType Label': [], 
+						'Receivable Voucher': ['posting_date', 'debit_to', 'project_name'], 
+						'GL Entry': ['posting_date', 'account', 'voucher_no'], 
+						'Serial No': ['status', 'warehouse'], 
+						'Delivery Note': ['posting_date', 'project_name', 'customer'], 
+						'UOM Conversion Detail': ['uom'], 
+						'Search Criteria': ['criteria_name'], 
+						'Salary Structure': [], 
+						'Educational Qualifications': ['qualification'], 
+						'TDS Rate Chart': ['applicable_from', 'applicable_to'], 
+						'GL Mapper': [], 
+						'Announcement': [], 
+						'Call Log Details': [], 
+						'Enquiry': ['lead', 'customer', 'transaction_date'], 
+						'Flat BOM Detail': ['item_code'], 
+						'Landed Cost Detail': ['account_head'], 
+						'Field Mapper Detail': ['from_field', 'to_field'], 
+						'File Data': [], 
+						'Question Tag': [], 
+						'QA Inspection Report': ['item_code', 'purchase_receipt_no', 'report_date'], 
+						'Appraisal Detail': [], 
+						'POS Settings': ['territory'], 
+						'Delivery Note Detail': ['item_code', 'prevdoc_docname', 'warehouse', 'prevdoc_detail_docname'], 
+						'Profile': [], 
+						'Other Income Detail': [], 
+						'Product': ['item_code', 'stock_warehouse'], 
+						'PO Detail': ['prevdoc_docname', 'item_code', 'prevdoc_detail_docname', 'warehouse'], 
+						'Module Def Role': ['role'], 
+						'Sales Team': ['sales_person'], 
+						'Enquiry Detail': ['item_code'], 
+						'DocType': [], 
+						'Compaint Note': ['nature_of_complaint', 'compliance_date'], 
+						'Maintenance Schedule': ['customer', 'sales_order_no'], 
+						'Event User': ['person'], 
+						'Stock Reconciliation': ['reconciliation_date'], 
+						'Purchase Receipt': ['posting_date', 'supplier', 'project_name'], 
+						'Complaint Detail': ['item_name'], 
+						'Address': ['customer', 'supplier'], 
+						'Ticket': ['request_date', 'allocated_to', 'category', 'customer', 'project'], 
+						'Territory Target Detail': ['month', 'fiscal_year'], 
+						'LC PR Detail': ['purchase_receipt_no'], 
+						'Customer': ['customer_name', 'customer_group'], 
+						'PP SO Detail': [], 
+						'PP Detail': ['document_date', 'item_code', 'parent_item'], 
+						'User Setting-Role Permission': [], 
+						'Custom Script': ['dt'], 
+						'Country': [], 
+						'DefaultValue': [], 
+						'Ledger Detail': [], 
+						'SS Earning Detail': ['e_type'], 
+						'SMS Log': [], 
+						'Expense Type': [], 
+						'Item': ['item_group'], 
+						'Fiscal Year': [], 
+						'ToDo Item': ['role'], 
+						'Payable Voucher': ['posting_date', 'credit_to', 'project_name', 'supplier'], 
+						'Journal Voucher Detail': ['account', 'against_voucher', 'against_invoice', 'against_jv'], 
+						'Online Contact': [], 
+						'Page': ['module'], 
+						'Leave Application': ['employee', 'leave_type', 'from_date', 'to_date'], 
+						'Expense Voucher Detail': ['expense_type'], 
+						'Maintenance Visit': ['customer', 'sales_order_no', 'customer_issue_no'], 
+						'Ref Rate Detail': ['price_list_name', 'ref_currency'], 
+						'Receiver Detail': [], 
+						'Naming Series Options': ['doc_type'], 
+						'Activity Type': [], 
+						'PRO PP Detail': [], 
+						'Delivery Note Packing Detail': ['item_code', 'parent_item', 'warehouse'], 
+						'Workflow Rule': ['select_form'], 
+						'File': ['file_group'], 
+						'Item Maintenance Detail': ['item_code', 'start_date', 'end_date', 'prevdoc_docname'], 
+						'Purchase Order': ['supplier', 'project_name', 'posting_date'], 
+						'Print Heading': [], 
+						'TDS Rate Detail': ['category']
+					}
+	#sql("commit") # only required if run from login
+	exist_dt = [cstr(d[0]) for d in sql("select name from `tabDocType`")]
+	
+	for dt in [d for d in dt_index_fields.keys() if d in exist_dt]:
+		try:
+			current_index = sql("show indexes from `tab%s`" % dt)
+	
+			proper_index = dt_index_fields[dt]
+	
+			for d in current_index:
+				if d[4] not in ['name', 'parent', 'parenttype']:
+					if d[4] not in proper_index:
+						sql("ALTER TABLE `tab%s` DROP INDEX %s" % (dt, d[4]))
+						sql("start transaction")
+						sql("UPDATE `tabDocField` SET search_index = 0 WHERE fieldname = '%s' AND parent = '%s'" % (d[4], dt))
+						sql("commit")
+					else:
+						proper_index.remove(d[4])
+	
+			for d in proper_index:
+				sql("ALTER TABLE `tab%s` ADD INDEX ( `%s` ) " % (dt, d))
+				sql("start transaction")
+				sql("UPDATE `tabDocField` SET search_index = 1 WHERE fieldname = '%s' AND parent = '%s'" % (d, dt))
+				sql("commit")
+		except:
+			continue
diff --git a/erpnext/patches/old_patches/__init__.py b/erpnext/patches/old_patches/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/patches/old_patches/__init__.py
diff --git a/erpnext/patches/old_patches/customer_address.py b/erpnext/patches/old_patches/customer_address.py
new file mode 100644
index 0000000..41c97b8
--- /dev/null
+++ b/erpnext/patches/old_patches/customer_address.py
@@ -0,0 +1,688 @@
+import webnotes
+
+from webnotes.model.doc import Document
+from webnotes.utils import load_json, cint, cstr
+from webnotes import msgprint, errprint
+
+def make_address():
+	from webnotes.modules.module_manager import reload_doc
+	reload_doc('utilities','doctype','address')
+	
+	from webnotes.model.db_schema import updatedb
+	updatedb('Address')
+
+def make_address_from_customer():
+	for c in webnotes.conn.sql("select * from tabCustomer", as_dict=1):		
+		d = Document('Address') 
+		d.address_line1 = c['address_line1'] 
+		d.address_line2 = c['address_line2']  
+		d.city = c['city']  
+		d.country = c['country']  
+		d.pincode = c['pincode']
+		d.state = c['state']  
+		d.fax = c['fax_1']  
+		d.email_id = c['email_id']  		
+		d.phone = c['phone_1']  
+		d.customer = c['name']  
+		d.customer_name = c['customer_name']  
+		d.is_primary_address = 1
+		d.address_type = 'Office'
+		try:
+			d.save(1)
+		except NameError, e:
+			pass
+
+def make_address_from_supplier():
+	for c in webnotes.conn.sql("select * from tabSupplier", as_dict=1):		
+		d = Document('Address')
+		d.address_line1 = c['address_line1'] 
+		d.address_line2 = c['address_line2']  
+		d.city = c['city']  
+		d.country = c['country']  
+		d.pincode = c['pincode']
+		d.state = c['state']  		  		
+		d.supplier = c['name']  
+		d.supplier_name = c['supplier_name']  
+		d.is_primary_address = 1
+		d.address_type = 'Office'
+		try:
+			d.save(1)
+		except NameError, e:
+			pass
+
+def make_contact_from_contacttab():
+	webnotes.conn.sql("""
+	update ignore tabContact set
+		is_primary_contact = if(is_primary_contact='Yes',1,0)
+	""")
+
+	webnotes.conn.sql("""
+	update ignore tabContact t1, tabCustomer t2 set
+		t1.name = concat(ifnull(t1.contact_name,t1.name), '-', ifnull(t1.customer_name, t2.name))
+		where ifnull(t1.is_customer,0)=1
+		and t1.customer = t2.name
+	""")
+
+	webnotes.conn.sql("""
+	update ignore tabContact t1, tabSupplier t2 set
+		t1.name = concat(ifnull(t1.contact_name,t1.name), '-', ifnull(t1.supplier_name, t2.name))
+		where ifnull(t1.is_supplier,0)=1
+		and t1.supplier = t2.name
+	""")
+
+	webnotes.conn.sql("""
+	update ignore tabContact set
+		name = concat(ifnull(contact_name,name), '-', sales_partner)
+		where ifnull(is_sales_partner,0)=1
+	""")
+
+	webnotes.conn.commit()
+	try:
+		webnotes.conn.sql("""alter table tabContact change contact_no phone varchar(180)""")
+		webnotes.conn.sql("""alter table tabContact change is_primary_contact is_primary_contact int(1)""")
+	except:
+		pass
+	webnotes.conn.begin()
+	
+def delete_unwanted_fields():
+	delete_fields = [
+		('Contact', 'is_sales_partner'), ('Contact', 'sales_partner_address'), ('Contact', 'partner_type'), ('Contact', 'disable_login'), ('Contact', 'contact_address'), ('Contact', 'fax'), ('Contact', 'company_name'), ('Contact', 'contact_no'), ('Contact', 'customer_group'), ('Contact', 'has_login'), ('Contact', 'Create Login'), ('Contact', 'contact_name'), ('Contact', 'company_address'), ('Contact', 'customer_address'), ('Contact', 'supplier_address'), ('Contact', 'supplier_type'), ('Contact', 'is_customer'), ('Contact', 'is_supplier'), ('Contact', 'employee_id'), ('Contact', 'is_employee'), 
+		('Customer', 'region'), ('Customer', 'pincode'), ('Customer', 'city'), ('Customer', 'country'), ('Customer', 'state'), ('Customer', 'address'), ('Customer', 'telephone'), ('Customer', 'address_line2'), ('Customer', 'address_line1'), ('Customer', 'last_sales_order'), ('Customer', 'Shipping HTML'), ('Customer', 'phone_1'), ('Customer', 'Territory Help'), ('Customer', 'CG Help'), ('Customer', 'fax_1'), ('Customer', 'email_id'), 
+		('Customer Issue', 'email_id'), ('Customer Issue', 'contact_no'),
+		('Delivery Note', 'customer_mobile_no'), ('Delivery Note', 'Send SMS'), ('Delivery Note', 'Get Other Charges'), ('Delivery Note', 'message'), ('Delivery Note', 'shipping_address'), ('Delivery Note', 'ship_to'), ('Delivery Note', 'ship_det_no'), ('Delivery Note', 'contact_no'), ('Delivery Note', 'Customer Details'), ('Delivery Note', 'email_id'), ('Delivery Note', 'delivery_address'), ('Delivery Note', 'Contact Help'), ('Delivery Note', 'Territory Help'), 
+		('Enquiry', 'address'), ('Enquiry', 'Send Email'), ('Enquiry', 'enquiry_attachment_detail'), ('Enquiry', 'contact_date_ref'), ('Enquiry', 'Update Follow up'), ('Enquiry', 'email_id1'), ('Enquiry', 'cc_to'), ('Enquiry', 'subject'), ('Enquiry', 'message'), ('Enquiry', 'Attachment Html'), ('Enquiry', 'Create New File'), ('Enquiry', 'contact_no'), ('Enquiry', 'email_id'), ('Enquiry', 'project'), ('Enquiry', 'update_follow_up'), ('Enquiry', 'Contact Help'), 
+		('Installation Note', 'address'), 
+		('Lead', 'message'), ('Lead', 'Send Email'), ('Lead', 'address'), ('Lead', 'subject'), ('Lead', 'contact_no'), ('Lead', 'TerritoryHelp'), 
+		('Maintenance Schedule', 'address'), 
+		('Maintenance Visit', 'address'), 
+		('Purchase Order', 'Contact Help'), ('Purchase Order', 'supplier_qtn'), ('Purchase Order', 'contact_no'), ('Purchase Order', 'email'), 
+		('Purchase Receipt', 'Contact Help'), 
+		('Quotation', 'email_id'), ('Quotation', 'contact_no'), ('Quotation', 'Update Follow up'), ('Quotation', 'contact_date_ref'), ('Quotation', 'Territory Help'), ('Quotation', 'Contact Help'), 
+		('Receivable Voucher', 'Territory Help'), 
+		('Sales Order', 'contact_no'), ('Sales Order', 'email_id'), ('Sales Order', 'Contact Help'), ('Sales Order', 'file_list'), ('Sales Order', 'ship_det_no'), ('Sales Order', 'mobile_no'), ('Sales Order', 'Territory Help'), ('Sales Order', 'ship_to'), ('Sales Order', 'Customer Details'), 
+		('Sales Partner', 'area_code'), ('Sales Partner', 'telephone'), ('Sales Partner', 'email'), ('Sales Partner', 'address'), ('Sales Partner', 'TerritoryHelp'), ('Sales Partner', 'pincode'), ('Sales Partner', 'country'), ('Sales Partner', 'city'), ('Sales Partner', 'address_line2'), ('Sales Partner', 'address_line1'), ('Sales Partner', 'mobile'), ('Sales Partner', 'state'), 
+		('Serial No', 'supplier_address'), 
+		('Supplier', 'city'), ('Supplier', 'country'), ('Supplier', 'state'), ('Supplier', 'address_line1'), ('Supplier', 'last_purchase_order'), ('Supplier', 'address'), ('Supplier', 'address_line2'), ('Supplier', 'pincode'), ('Supplier rating', 'address'), ('Supplier rating', 'select'), ('Supplier rating', 'supplier')]
+	for d in delete_fields:
+		webnotes.conn.sql("delete from tabDocField where parent=%s and if(ifnull(fieldname,'')='',ifnull(label,''),fieldname)=%s", (d[0], d[1]))
+
+#def gen_txt_files():
+#	from webnotes.modules.export_module import export_to_files
+#	for dt in ['Contact','Customer','Customer Issue','Delivery Note','Enquiry','Installation Note','Lead','Maintenance Schedule','Maintenance Visit','Purchase Order','Purchase Receipt','Quotation','Receivable Voucher','Sales Order','Sales Partner','Serial No','Supplier']:
+#		export_to_files(record_list=[['DocType',dt]])
+
+def reload_doc_files():
+	from webnotes.modules.module_manager import reload_doc	
+	reload_doc('utilities', 'doctype', 'contact')
+	reload_doc('selling', 'doctype', 'customer')
+	reload_doc('support', 'doctype', 'customer_issue')
+	reload_doc('stock', 'doctype', 'delivery_note')
+	reload_doc('selling', 'doctype', 'enquiry')
+	reload_doc('selling', 'doctype', 'installation_note')
+	reload_doc('selling', 'doctype', 'lead')
+	reload_doc('support', 'doctype', 'maintenance_schedule')
+	reload_doc('support', 'doctype', 'maintenance_visit')
+	reload_doc('buying', 'doctype', 'purchase_order')
+	reload_doc('stock', 'doctype', 'purchase_receipt')
+	reload_doc('selling', 'doctype', 'quotation')
+	reload_doc('accounts', 'doctype', 'receivable_voucher')
+	reload_doc('accounts', 'doctype', 'payable_voucher')	
+	reload_doc('selling', 'doctype', 'sales_order')
+	reload_doc('setup', 'doctype', 'sales_partner')
+	reload_doc('stock', 'doctype', 'serial_no')
+	reload_doc('buying', 'doctype', 'supplier')
+	
+def reload_mapper_files():
+	from webnotes.modules.module_manager import reload_doc	
+	reload_doc('Mapper', 'DocType Mapper', 'Customer Issue-Maintenance Visit')
+	reload_doc('Mapper', 'DocType Mapper', 'Delivery Note-Installation Note')
+	reload_doc('Mapper', 'DocType Mapper', 'Delivery Note-Receivable Voucher')
+	reload_doc('Mapper', 'DocType Mapper', 'Enquiry-Quotation')
+	reload_doc('Mapper', 'DocType Mapper', 'Lead-Customer')
+	reload_doc('Mapper', 'DocType Mapper', 'Lead-Enquiry')
+	reload_doc('Mapper', 'DocType Mapper', 'Purchase Order-Payable Voucher')
+	reload_doc('Mapper', 'DocType Mapper', 'Purchase Order-Purchase Receipt')
+	reload_doc('Mapper', 'DocType Mapper', 'Purchase Receipt-Payable Voucher')
+	reload_doc('Mapper', 'DocType Mapper', 'Quotation-Sales Order')
+	reload_doc('Mapper', 'DocType Mapper', 'Receivable Voucher-Delivery Note')
+	reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Delivery Note')
+	reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Maintenance Schedule')
+	reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Maintenance Visit')
+	reload_doc('Mapper', 'DocType Mapper', 'Sales Order-Receivable Voucher')		
+  	
+def delete_unwanted_mapper_fields():
+	delete_fields = [
+	('Customer Issue-Maintenance Visit', 'customer_address', 'address'),
+	('Delivery Note-Installation Note', 'customer_address', 'address'),
+	('Enquiry-Quotation', 'contact_no', 'contact_no'), ('Enquiry-Quotation', 'subject', 'enq_det'), ('Enquiry-Quotation', 'customer_name', 'customer_name'), ('Enquiry-Quotation', 'customer_name', 'customer_name'), ('Enquiry-Quotation', 'address', 'customer_address'), ('Enquiry-Quotation', 'email_id', 'email_id'),
+	('Quotation-Sales Order', 'contact_no', 'contact_no'), ('Quotation-Sales Order', 'email_id', 'email_id'), ('Quotation-Sales Order', 'customer_mobile_no', 'customer_mobile_no'),
+	('Sales Order-Delivery Note', 'customer_address', 'delivery_address'), ('Sales Order-Delivery Note', 'customer_address', 'customer_address'), ('Sales Order-Delivery Note', 'contact_no', 'contact_no'), ('Sales Order-Delivery Note', 'email_id', 'email_id'), ('Sales Order-Delivery Note', 'ship_det_no', 'ship_det_no'), ('Sales Order-Delivery Note', 'ship_to', 'ship_to'), ('Sales Order-Delivery Note', 'shipping_address', 'shipping_address'), ('Sales Order-Delivery Note', 'customer_mobile_no', 'customer_mobile_no'),
+	('Sales Order-Maintenance Schedule', 'customer_address', 'address'),
+	('Sales Order-Maintenance Visit', 'customer_address', 'address'),
+	('Sales Order-Receivable Voucher', 'contact_no', 'contact_no')]
+	
+  	for rec in delete_fields:  		
+		webnotes.conn.sql("delete from `tabField Mapper Detail` where parent=%s and from_field=%s and to_field=%s",(rec[0], rec[1], rec[2]))
+  	
+def sync_docfield_properties():
+	update_fields = [	
+	('Contact', 'customer', 'Customer', 0L, None, 0L, None), ('Contact', 'supplier', 'Supplier', 0L, None, None, None), ('Contact', 'is_primary_contact', None, 0L, None, None, None), ('Contact', 'email_id', None, 0L, 1L, None, None), ('Contact', 'department', 'Suggest', 0L, None, None, None), ('Contact', 'designation', 'Suggest', 0L, None, None, None),
+	('Customer Issue', 'customer', 'Customer', 0L, 1L, 1L, None), ('Customer Issue', 'customer_address', 'Address', 0L, None, 1L, None), ('Customer Issue', 'contact_person', 'Contact', 0L, None, 1L, None), ('Customer Issue', 'customer_name', None, 1L, None, None, None), ('Customer Issue', 'company', 'Company', 0L, 1L, 1L, None), ('Customer Issue', 'fiscal_year', 'link:Fiscal Year', 0L, 1L, 1L, None),
+	('Delivery Note', 'customer_address', 'Address', 0L, None, 1L, None), ('Delivery Note', 'contact_person', 'Contact', 0L, None, 1L, None), ('Delivery Note', 'customer_name', None, 1L, None, None, None), ('Delivery Note', 'status', '\nDraft\nSubmitted\nCancelled', 1L, 1L, 1L, None), ('Delivery Note', 'territory', 'Territory', 0L, 1L, 1L, 0L), ('Delivery Note', 'customer_group', 'Customer Group', 0L, None, 1L, None), ('Delivery Note', 'transporter_name', None, 0L, 0L, 1L, None), ('Delivery Note', 'lr_no', None, 0L, 0L, 1L, None), ('Delivery Note', 'lr_date', None, 0L, None, 1L, None), ('Delivery Note', 'currency', 'link:Currency', 0L, 1L, 1L, None), ('Delivery Note', 'letter_head', 'link:Letter Head', 0L, None, 1L, None),
+	('Enquiry', 'contact_person', 'Contact', 0L, None, 1L, None), ('Enquiry', 'customer_name', None, 1L, None, 0L, None), ('Enquiry', 'lead', 'Lead', 0L, None, 1L, 0L), ('Enquiry', 'enquiry_type', '\nSales\nMaintenance', 0L, 1L, None, None), ('Enquiry', 'territory', 'Territory', 0L, 1L, 1L, None), ('Enquiry', 'customer_group', 'Customer Group', 0L, 0L, 1L, 0L), ('Enquiry', 'contact_by', 'Profile', 0L, None, None, None),
+	('Installation Note', 'contact_person', 'Contact', 0L, None, 1L, None), ('Installation Note', 'customer_name', None, 1L, 0L, None, None), ('Installation Note', 'territory', 'Territory', 0L, 1L, 1L, None), ('Installation Note', 'status', 'Draft\nSubmitted\nCancelled', 1L, 1L, 1L, None),
+	('Lead', 'city', None, 0L, 1L, 1L, None), ('Lead', 'country', 'link:Country', 0L, 1L, 1L, None), ('Lead', 'state', 'Suggest', 0L, None, 1L, None), ('Lead', 'company', 'Company', 0L, 1L, None, None), ('Lead', 'contact_by', 'Profile', 0L, 0L, 0L, 0L),
+	('Maintenance Schedule', 'customer', 'Customer', 0L, 1L, 1L, None), ('Maintenance Schedule', 'contact_person', 'Contact', 0L, None, 1L, None), ('Maintenance Schedule', 'status', '\nDraft\nSubmitted\nCancelled', 1L, 1L, None, None), ('Maintenance Schedule', 'territory', 'Territory', 0L, 1L, None, None),
+	('Maintenance Visit', 'customer', 'Customer', 0L, 1L, 1L, None), ('Maintenance Visit', 'contact_person', 'Contact', 0L, None, 1L, None), ('Maintenance Visit', 'customer_name', None, 1L, None, None, None), ('Maintenance Visit', 'company', 'link:Company', 0L, 1L, 1L, None), ('Maintenance Visit', 'fiscal_year', 'link:Fiscal Year', 0L, 1L, 1L, None), ('Maintenance Visit', 'status', '\nDraft\nCancelled\nSubmitted', 1L, 1L, None, None), ('Maintenance Visit', 'territory', 'Territory', 0L, None, 1L, None),
+	('Purchase Order', 'supplier_address', 'Address', 0L, None, 1L, None), ('Purchase Order', 'contact_person', 'Contact', 0L, None, 1L, None), ('Purchase Order', 'supplier_name', None, 1L, None, None, None), ('Purchase Order', 'status', '\nDraft\nSubmitted\nStopped\nCancelled', 1L, 1L, 1L, None), ('Purchase Order', 'indent_no', 'Indent', 0L, None, 1L, 0L), ('Purchase Order', 'is_subcontracted', '\nYes\nNo', 0L, None, 1L, None), ('Purchase Order', 'currency', 'link:Currency', 0L, 1L, 1L, None), ('Purchase Order', 'net_total', None, 1L, 0L, 1L, None),
+	('Purchase Receipt', 'supplier_address', 'Address', 0L, None, 1L, None), ('Purchase Receipt', 'contact_person', 'Contact', 0L, None, 1L, None), ('Purchase Receipt', 'supplier_name', None, 1L, None, None, None), ('Purchase Receipt', 'status', '\nDraft\nSubmitted\nCancelled', 1L, 1L, 1L, None), ('Purchase Receipt', 'currency', 'link:Currency', 0L, 1L, 1L, None),
+	('Quotation', 'customer', 'Customer', 0L, None, 1L, 0L), ('Quotation', 'customer_address', 'Address', 0L, None, 1L, 0L), ('Quotation', 'contact_person', 'Contact', 0L, 0L, 1L, 0L), ('Quotation', 'customer_name', None, 1L, None, None, None), ('Quotation', 'lead', 'Lead', 0L, None, 1L, 0L), ('Quotation', 'lead_name', None, 1L, None, None, None), ('Quotation', 'order_type', '\nSales\nMaintenance', 0L, 1L, 0L, None), ('Quotation', 'status', '\nDraft\nSubmitted\nOrder Confirmed\nOrder Lost\nCancelled', 1L, 1L, 1L, None), ('Quotation', 'territory', 'Territory', 0L, 1L, 1L, 0L), ('Quotation', 'currency', 'link:Currency', 0L, 1L, 1L, None), ('Quotation', 'letter_head', 'link:Letter Head', 0L, None, 1L, None), ('Quotation', 'order_lost_reason', None, 1L, None, 1L, None), ('Quotation', 'contact_by', 'Profile', 0L, None, 1L, None), ('Quotation', 'contact_date', None, 0L, None, 1L, None), ('Quotation', 'to_discuss', None, 0L, None, 1L, None),
+	('Receivable Voucher', 'debit_to', 'Account', 0L, 1L, 1L, None), ('Receivable Voucher', 'customer_address', 'Address', 0L, None, 1L, None), ('Receivable Voucher', 'territory', 'Territory', 0L, 1L, 1L, None), ('Receivable Voucher', 'paid_amount', None, 0L, None, 1L, None), ('Receivable Voucher', 'company', 'Company', 0L, 1L, 1L, None), ('Receivable Voucher', 'fiscal_year', 'link:Fiscal Year', 0L, 1L, 1L, None), ('Receivable Voucher', 'outstanding_amount', None, 1L, None, 1L, None),
+	('Payable Voucher', 'supplier_address', 'Address', 0L, None, 1L, None), ('Payable Voucher', 'contact_display', None, 1L, None, None, None), ('Payable Voucher', 'contact_mobile', None, 1L, None, None, None), ('Payable Voucher', 'contact_email', None, 1L, None, 1L, None), ('Payable Voucher', 'currency', 'link:Currency', 0L, 1L, 1L, None), ('Payable Voucher', 'conversion_rate', None, 0L, 1L, 1L, None), ('Payable Voucher', 'company', 'Company', 0L, 1L, 1L, None), ('Payable Voucher', 'fiscal_year', 'link:Fiscal Year', 0L, 1L, 1L, None),
+	('Sales Order', 'customer_address', 'Address', 0L, None, 1L, 0L), ('Sales Order', 'contact_person', 'Contact', 0L, None, 1L, None), ('Sales Order', 'customer_name', None, 1L, None, None, None), ('Sales Order', 'status', '\nDraft\nSubmitted\nStopped\nCancelled', 1L, 1L, 1L, None), ('Sales Order', 'quotation_date', None, 1L, 0L, 1L, 1L), ('Sales Order', 'currency', 'link:Currency', 0L, 1L, 1L, None), ('Sales Order', 'letter_head', 'link:Letter Head', 0L, None, 1L, None),
+	('Sales Partner', 'territory', 'Territory', 0L, 1L, None, None),
+	('Supplier', 'company', 'Company', 0L, 1L, None, None)]
+	
+	for rec in update_fields:
+		webnotes.conn.sql("UPDATE `tabDocField` SET options=%s, permlevel=%s, reqd=%s, print_hide=%s, hidden=%s where parent=%s and fieldname=%s",(rec[2], rec[3], rec[4], rec[5], rec[6], rec[0], rec[1]))
+	
+def run_patch():
+	make_address()
+  	make_address_from_customer()
+  	make_address_from_supplier()
+  	make_contact_from_contacttab()
+  	delete_unwanted_fields()
+	reload_doc_files()
+	reload_mapper_files()
+	delete_unwanted_mapper_fields()
+	sync_docfield_properties()	
+
+#Old Customer Data Sync Patch for "Quotation, SO, PO, RV, PV, DN, PR, Installation Note, Maintenance Schedule, Customer Issue, Maintenance Visit"
+#--------------------------------------------------------------
+
+def run_old_data_sync_patch():
+	sync_quotation_customer_data()
+	sync_sales_order_customer_data()
+	sync_purchase_order_supplier_data()
+	sync_receivable_voucher_customer_data()
+	sync_payable_voucher_supplier_data()
+	sync_delivery_note_customer_data()
+	sync_purchase_receipt_supplier_data()
+	sync_installation_note_customer_data()
+	sync_maintenance_schedule_customer_data()
+	sync_customer_issue_customer_data()
+	sync_maintenance_visit_customer_data()
+	sync_lead_phone()
+	
+#Quotation
+def sync_quotation_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT tq.name as id,tq.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM tabQuotation tq, tabAddress ta
+	WHERE tq.customer = ta.customer
+	AND tq.quotation_to = 'Customer'	
+	AND tq.docstatus !=2
+	ORDER BY tq.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))											
+		
+		webnotes.conn.sql("""
+		UPDATE tabQuotation SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))
+		
+	data_rec = webnotes.conn.sql("""
+	SELECT tq.name as id,tq.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM tabQuotation tq, tabContact tc
+	WHERE tq.customer = tc.customer 
+	AND tq.quotation_to = 'Customer'	
+	AND tq.docstatus !=2
+	ORDER BY tq.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE tabQuotation SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))
+				
+		
+#Sales Order		
+def sync_sales_order_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabSales Order` t, tabAddress ta
+	WHERE t.customer = ta.customer
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Phone: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabSales Order` SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))		
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabSales Order` t, tabContact tc
+	WHERE t.customer = tc.customer 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:					
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabSales Order` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))		
+				
+#Purchase Order
+def sync_purchase_order_supplier_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.supplier, 
+	ta.name as supplier_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabPurchase Order` t, tabAddress ta
+	WHERE t.supplier = ta.supplier
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabPurchase Order` SET
+			supplier_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['supplier_address'],address_display,rec['id']))				
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.supplier, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabPurchase Order` t, tabContact tc
+	WHERE t.supplier = tc.supplier 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:					
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabPurchase Order` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))				
+		
+#Sales Invoice		
+def sync_receivable_voucher_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabReceivable Voucher` t, tabAddress ta
+	WHERE t.customer = ta.customer
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabReceivable Voucher` SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))		
+		
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabReceivable Voucher` t, tabContact tc
+	WHERE t.customer = tc.customer 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:					
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabReceivable Voucher` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))				
+		
+#Purchase Invoice
+def sync_payable_voucher_supplier_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.supplier, 
+	ta.name as supplier_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabPayable Voucher` t, tabAddress ta
+	WHERE t.supplier = ta.supplier
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabPayable Voucher` SET
+			supplier_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['supplier_address'],address_display,rec['id']))				
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.supplier, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabPayable Voucher` t, tabContact tc
+	WHERE t.supplier = tc.supplier 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:					
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabPayable Voucher` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))				
+		
+#Delivery Note
+def sync_delivery_note_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabDelivery Note` t, tabAddress ta
+	WHERE t.customer = ta.customer
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabDelivery Note` SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))				
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabDelivery Note` t, tabContact tc
+	WHERE t.customer = tc.customer 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabDelivery Note` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))				
+
+#Purchase Receipt
+def sync_purchase_receipt_supplier_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.supplier, 
+	ta.name as supplier_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabPurchase Receipt` t, tabAddress ta
+	WHERE t.supplier = ta.supplier
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabPurchase Receipt` SET
+			supplier_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['supplier_address'],address_display,rec['id']))				
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.supplier, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabPurchase Receipt` t, tabContact tc
+	WHERE t.supplier = tc.supplier 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:					
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabPurchase Receipt` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))				
+
+#Installation Note
+def sync_installation_note_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabInstallation Note` t, tabAddress ta
+	WHERE t.customer = ta.customer
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabInstallation Note` SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))				
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabInstallation Note` t, tabContact tc
+	WHERE t.customer = tc.customer 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabInstallation Note` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))				
+		
+#Maintenance Schedule
+def sync_maintenance_schedule_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabMaintenance Schedule` t, tabAddress ta
+	WHERE t.customer = ta.customer
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabMaintenance Schedule` SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))	
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabMaintenance Schedule` t, tabContact tc
+	WHERE t.customer = tc.customer 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabMaintenance Schedule` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))	
+				
+#Customer Issue
+def sync_customer_issue_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabCustomer Issue` t, tabAddress ta
+	WHERE t.customer = ta.customer
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabCustomer Issue` SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabCustomer Issue` t, tabContact tc
+	WHERE t.customer = tc.customer 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabCustomer Issue` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))
+		
+#Maintenance Visit
+def sync_maintenance_visit_customer_data():
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	ta.name as customer_address, ta.address_line1, ta.address_line2, ta.city, ta.country, ta.pincode, ta.state, ta.phone
+	FROM `tabMaintenance Visit` t, tabAddress ta
+	WHERE t.customer = ta.customer
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		address_display = cstr((rec['address_line1'] and rec['address_line1'] or '')) + cstr((rec['address_line2'] and '\n' + rec['address_line2'] or '')) + cstr((rec['city'] and '\n'+rec['city'] or '')) + cstr((rec['pincode'] and ', ' + rec['pincode'] or '')) + cstr((rec['state'] and '\n'+rec['state']+', ' or '')) + cstr((rec['country'] and rec['country'] or '')) + '\n' + cstr((rec['phone'] and 'Tel: '+rec['phone'] or ''))
+											
+		webnotes.conn.sql("""
+		UPDATE `tabMaintenance Visit` SET
+			customer_address = %s,
+			address_display = %s
+			WHERE name = %s
+		""",(rec['customer_address'],address_display,rec['id']))	
+
+	data_rec = webnotes.conn.sql("""
+	SELECT t.name as id,t.customer, 
+	tc.name as contact_person, tc.first_name, tc.last_name, tc.email_id, tc.phone as contact_phone, tc.mobile_no, tc.department, tc.designation
+	FROM `tabMaintenance Visit` t, tabContact tc
+	WHERE t.customer = tc.customer 
+	AND t.docstatus !=2
+	ORDER BY t.name
+	""", as_dict=1)
+	
+	for rec in data_rec:			
+		contact_display = (rec['first_name'] and rec['first_name'] or '') + (rec['last_name'] and ' ' + rec['last_name'] or '')
+											
+		webnotes.conn.sql("""
+		UPDATE `tabMaintenance Visit` SET
+			contact_person = %s,
+			contact_mobile = %s,
+			contact_email = %s,
+			contact_display = %s			
+			WHERE name = %s
+		""",(rec['contact_person'],rec['mobile_no'],rec['email_id'],contact_display,rec['id']))			
+
+#lead phone data sync
+def sync_lead_phone():
+	webnotes.conn.sql("""
+		update ignore tabLead set
+			phone = contact_no
+			where contact_no is not null			
+		""")
diff --git a/erpnext/patches/old_patches/doctype_permission_patch.py b/erpnext/patches/old_patches/doctype_permission_patch.py
new file mode 100644
index 0000000..2bb7cf1
--- /dev/null
+++ b/erpnext/patches/old_patches/doctype_permission_patch.py
@@ -0,0 +1,74 @@
+import webnotes
+
+def set_doctype_permissions():
+	
+	# remove descriptions
+	webnotes.conn.sql("update tabDocType set description=null")
+		
+	from webnotes.modules.module_manager import reload_doc
+	reload_doc('core','doctype','custom_script')
+	reload_doc('core','doctype','custom_field')
+	reload_doc('core','doctype','property_setter')
+	
+	# remove admin rights
+	webnotes.conn.sql("delete from tabUserRole where role in ('Administrator','Customer','Supplier') and parent!='Administrator'")	
+	
+	# create custom scripts
+	create_custom_scripts()
+
+	# remove script fields
+	reload_doc('core','doctype','doctype')
+
+	# allow sys manager to read doctype, custom script
+	allow_sys_manager()
+	
+def create_custom_scripts():
+	
+	cs_list = webnotes.conn.sql("select name, server_code, client_script from tabDocType where ifnull(server_code,'')!='' or ifnull(client_script,'')!=''")
+	
+	from webnotes.model.doc import Document
+	
+	for c in cs_list:
+		if c[1]:
+			cs = Document('Custom Script')
+			cs.dt = c[0]
+			cs.script_type = 'Server'
+			cs.script = c[1]
+			try:
+				cs.save(1)
+			except NameError:
+				pass
+
+		if c[2]:
+			cs = Document('Custom Script')
+			cs.dt = c[0]
+			cs.script_type = 'Client'
+			cs.script = c[2]
+			try:
+				cs.save(1)
+			except NameError:
+				pass
+
+def allow_sys_manager():
+	from webnotes.model.doc import Document
+
+	if not webnotes.conn.sql("select name from tabDocPerm where parent='DocType' and role='System Manager' and `read`=1"):
+		d = Document('DocPerm')
+		d.parent = 'DocType'
+		d.parenttype = 'DocType'
+		d.parentfield = 'permissions'
+		d.role = 'System Manager'
+		d.read = 1
+		d.save(1)
+
+	
+	if not webnotes.conn.sql("select name from tabDocPerm where parent='Custom Script' and role='System Manager' and `write`=1"):
+		d = Document('DocPerm')
+		d.parent = 'Custom Script'
+		d.parenttype = 'DocType'
+		d.parentfield = 'permissions'
+		d.role = 'System Manager'
+		d.read = 1
+		d.write = 1
+		d.create = 1
+		d.save(1)
\ No newline at end of file
diff --git a/erpnext/patches/old_patches/feed_patch.py b/erpnext/patches/old_patches/feed_patch.py
new file mode 100644
index 0000000..9d8ab0b
--- /dev/null
+++ b/erpnext/patches/old_patches/feed_patch.py
@@ -0,0 +1,102 @@
+# long patches
+import webnotes
+
+def set_subjects_and_tagfields():
+	subject_dict = {
+		'Item':'%(item_name)s',
+		'Customer':' ',
+		'Contact':'%(first_name)s %(last_name)s - Email: %(email_id)s | Contact: %(contact_no)s',
+		'Supplier':' ',
+		'Lead':'%(lead_name)s from %(company_name)s | To Discuss: %(to_discuss)s',
+		'Quotation':'To %(customer_name)s on %(transaction_date)s worth %(currency)s %(grand_total_export)s',
+		'Enquiry':'To %(customer_name)s%(lead_name)s on %(transaction_date)s',
+		'Sales Order':'From %(customer_name)s on %(transaction_date)s worth %(currency)s %(grand_total_export)s | %(per_delivered)s% delivered | %(per_billed)s% billed',
+		'Delivery Note':'To %(customer_name)s on %(transaction_date)s | %(per_billed)s% billed',
+		'Indent':'%(per_ordered)s% ordered',
+		'Purchase Order':'To %(supplier_name)s on %(transaction_date)s | %(per_received)s% delivered',
+		'Purchase Receipt':'From %(supplier_name)s against %(purchase_order)s on %(transaction_date)s',
+		'Receivable Voucher':'To %(customer_name)s worth %(currency)s %(grand_total_export)s due on %(due_date)s | %(outstanding_amount)s outstanding',
+		'Payable Voucher':'From %(supplier_name)s due on %(due_date)s | %(outstanding_amount)s outstanding',
+		'Journal Voucher':' ',
+		'Serial No':'%(item_code)s',
+		'Project':' ',
+		'Ticket':'%(subject)s',
+		'Timesheet':'%(owner)s',
+		'Support Ticket':'%(problem_description)s',
+		'Installation Note':'At %(customer_name)s on %(inst_date)s',
+		'Maintenance Visit':'To %(customer_name)s on %(mntc_date)s',
+		'Customer Issue':'%(complaint)s By %(complaint_raised_by)s on %(issue_date)s',
+		'Employee':'%(employee_name)s',
+		'Expense Voucher':'From %(employee_name)s for %(total_claimed_amount)s (claimed)',
+		'Appraisal':'',
+		'Leave Application':'From %(employee_name)s, %(designation)s',
+		'Salary Structure':'For %(employee_name)s',
+		'Salary Slip':'For %(employee_name)s, %(designation)s',
+		'Bill of Materials':'%(item_code)s'
+	}
+	
+	tags_dict = {
+		'Item':'item_group',
+		'Customer':'customer_group,customer_type',
+		#'Contact':'',
+		'Supplier':'supplier_type',
+		'Lead':'status,source',
+		'Quotation':'status',
+		'Enquiry':'',
+		'Sales Order':'status',
+		'Delivery Note':'',
+		'Indent':'',
+		'Purchase Order':'',
+		'Purchase Receipt':'',
+		'Receivable Voucher':'',
+		'Payable Voucher':'',
+		'Journal Voucher':'voucher_type',
+		'Serial No':'status',
+		'Project':'status',
+		'Ticket':'status',
+		'Timesheet':'',
+		'Support Ticket':'',
+		'Installation Note':'',
+		'Maintenance Visit':'completion_status,maintenance_type',
+		'Customer Issue':'status',
+		'Employee':'status',
+		'Expense Voucher':'approval_status',
+		'Appraisal':'',
+		'Leave Application':'leave_type',
+		'Salary Structure':'',
+		'Bill of Materials':''
+	}
+	
+	description_dict = {
+		'Property Setter':'Property Setter overrides a standard DocType or Field property',
+		'Custom Field':'Adds a custom field to a DocType',
+		'Custom Script':'Adds a custom script (client or server) to a DocType'
+	}
+	
+	alldt = []
+	
+	for dt in subject_dict:
+		webnotes.conn.sql('update tabDocType set subject=%s where name=%s', (subject_dict[dt], dt))
+		if not dt in alldt: alldt.append(dt)
+	
+	for dt in tags_dict:
+		webnotes.conn.sql('update tabDocType set tag_fields=%s where name=%s', (tags_dict[dt], dt))
+		if not dt in alldt: alldt.append(dt)
+
+	for dt in description_dict:
+		webnotes.conn.sql('update tabDocType set description=%s where name=%s', (description_dict[dt], dt))
+		if not dt in alldt: alldt.append(dt)
+	
+	#from webnotes.modules.export_module import export_to_files
+	#for dt in alldt:
+	#	export_to_files(record_list=[['DocType',dt]])
+
+def support_patch():
+	# relaod support and other doctypes
+	
+	from webnotes.modules.module_manager import reload_doc
+	
+	webnotes.model.delete_doc('DocType','Support Ticket')
+	reload_doc('setup','doctype','support_email_settings')
+	reload_doc('support','doctype','support_ticket')
+	reload_doc('support','doctype','support_ticket_response')
diff --git a/erpnext/patches/old_patches/patch_1.py b/erpnext/patches/old_patches/patch_1.py
new file mode 100644
index 0000000..9173ca5
--- /dev/null
+++ b/erpnext/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/erpnext/patches/old_patches/replacecode.py b/erpnext/patches/old_patches/replacecode.py
new file mode 100644
index 0000000..ff9e10d
--- /dev/null
+++ b/erpnext/patches/old_patches/replacecode.py
@@ -0,0 +1,19 @@
+import os
+
+def replace_code(old, new):
+	txt = os.popen("""grep "%s" ./*/*/*/*.js""" % old).read().split()
+	txt = [t.split(':')[0] for t in txt]
+	txt = list(set(filter(lambda t: t.startswith('./'), txt)))
+	for t in txt:
+		if new:
+			code = open(t,'r').read().replace(old, new)
+			open(t, 'w').write(code)
+			print "Replaced for %s" % t
+		else:
+			print 'Found in %s' % t
+	
+if __name__=='__main__':
+	old = """cur_frm.cscript.get_tips(doc, cdt, cdn);"""
+	new = " "
+	replace_code(old, new)
+			
diff --git a/erpnext/patches/patch.py b/erpnext/patches/patch.py
new file mode 100644
index 0000000..456e936
--- /dev/null
+++ b/erpnext/patches/patch.py
@@ -0,0 +1,458 @@
+# REMEMBER to update this
+# ========================
+
+last_patch = 385
+
+#-------------------------------------------
+
+def execute(patch_no):
+	import webnotes
+	from webnotes.modules.module_manager import reload_doc
+
+	from webnotes.model.code import get_obj
+	sql = webnotes.conn.sql
+	from webnotes.utils import cint, cstr, flt
+	from webnotes.model.doc import Document
+	from webnotes.model import delete_doc
+
+	if patch_no == 301:
+		from patches.delivery_billing_status_patch import run_patch
+		run_patch()
+	elif patch_no == 302:
+		sql("update `tabDocField` set no_copy = 1 where fieldname = 'naming_series'")
+	elif patch_no == 303:
+		pass
+	elif patch_no == 304:
+		sql("delete from `tabDocField` where parent = 'company' and label = 'Trash Company' and fieldtype = 'button'")
+		reload_doc('setup', 'doctype', 'company')
+	elif patch_no == 305:
+		sql("update `tabDocField` set options = 'link:Company' where options='link:Company' and fieldname='company' and fieldtype='Select'")
+	elif patch_no == 306:
+		sql("update `tabDocField` set options = '\nAccount\nCompany\nCustomer\nSupplier\nEmployee\nWarehouse\nItem' where parent = 'Rename Tool' and fieldname = 'select_doctype'")
+		sql("update `tabDocField` set options = 'link:Item' where parent = 'Raw Materials Supplied' and fieldname = 'po_item'")
+		sql("update `tabDocField` set options = 'Sales Order' where parent = 'Indent Detail' and fieldname = 'sales_order_no'")
+		sql("update `tabDocField` set options = 'link:Company', fieldtype = 'Select' where parent = 'Stock Ledger Entry' and fieldname = 'company'")
+		reload_doc('utilities', 'doctype', 'rename_tool')
+	elif patch_no == 307:
+		sql("delete from `tabDocField` where parent = 'company' and label = 'Trash Company' and fieldtype = 'Button'")
+		reload_doc('setup', 'doctype', 'company')
+	elif patch_no == 308:
+		sql("update `tabDocField` set reqd = 0 where fieldname = 'select_item' and parent = 'Property Setter'")
+	elif patch_no == 309:
+		sql("delete from `tabDocField` where fieldname = 'item_attachments_details' and parent = 'Item'")
+		sql("delete from `tabModule Def Item` where parent = 'Stock' and doc_name = 'Landed Cost Wizard'")
+	elif patch_no == 310:
+		from erpnext_structure_cleanup import run_patches
+		run_patches()
+	elif patch_no == 311:
+		sql("update `tabDocField` set reqd = 0 where fieldname = 'select_item' and parent = 'Property Setter'")
+		#reload_doc('core', 'doctype', 'property_setter')
+	elif patch_no == 312:
+		sql("delete from `tabSessions`")
+		sql("delete from `__SessionCache`")
+	elif patch_no == 313:
+		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-07-06 10: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-07-06 10: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]))
+
+
+		dt_list = ['Delivery Note', 'Purchase Receipt']
+		for dt in dt_list:
+			sql("update `tab%s` set status = 'Submitted' where docstatus = 1 and modified >='2011-07-06 10:00:00'" % dt)
+			sql("update `tab%s` set status = 'Cancelled' where docstatus = 2 and modified >='2011-07-06 10:00:00'" % dt)
+
+		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 == 314:
+		# delete double feed
+		sql("delete from tabFeed where subject like 'New %'")
+	elif patch_no == 315:
+		# delete double feed
+		sql("delete from tabFeed where doc_name like 'New %'")
+		reload_doc('core', 'doctype', 'property_setter')
+
+		from webnotes.model.doc import Document
+		m = Document('Module Def Role')
+		m.role = 'All'
+		m.parent = 'Home'
+		m.parenttype = 'Module Def'
+		m.parentfield = 'roles'
+		m.save(1)
+	elif patch_no == 316:
+		pass
+	elif patch_no == 317:
+		sql("update `tabPage` set name = 'profile-settings' where page_name = 'Profile Settings'")
+	elif patch_no == 318:
+		reload_doc('utilities', 'doctype', 'bulk_rename_tool')
+	elif patch_no == 319:
+		sql("delete from tabFeed where doc_name like 'New %'")
+	elif patch_no == 320:
+		reload_doc('setup', 'doctype', 'series_detail')
+	elif patch_no == 321:
+		reload_doc('hr','doctype','leave_application')
+	elif patch_no == 322:
+		sql("delete from `tabDocField` where parent = 'Leave Application' and fieldname = 'latter_head'")
+	elif patch_no == 323:
+		reload_doc('stock', 'doctype', 'stock_entry')
+		sql("update `tabDocField` set options = 'get_stock_and_rate' where parent = 'Stock Entry' and label = 'Get Stock and Rate'")
+		sql("delete from `tabDocField` where label = 'Get Current Stock' and parent = 'Stock Entry'")
+	elif patch_no == 324:
+		sql("delete from `tabDocField` where fieldname = 'test_field' and parent = 'Customer'")
+	elif patch_no == 325:
+		sql("update `tabDocField` set fieldtype = 'Data' where parent = 'Salary Slip' and fieldname = 'total_days_in_month'")
+		reload_doc('hr', 'doctype', 'salary_slip')
+	elif patch_no == 326:
+		# load the new billing page
+		if cint(webnotes.conn.get_value('Control Panel',None,'sync_with_gateway')):
+			reload_doc('server_tools','page','billing')
+	elif patch_no == 327:
+		# patch for support email settings now moved to email settings
+		reload_doc('setup','doctype','email_settings')
+
+		# map fields from support to email settings
+		field_map = {
+			'support_email': 'email',
+			'support_host':'host',
+			'support_username': 'username',
+			'support_password': 'password',
+			'support_use_ssl': 'use_ssl',
+			'sync_support_mails': 'integrate_incoming',
+			'signature': 'support_signature'
+		}
+
+		for key in field_map:
+			webnotes.conn.set_value('Email Settings',None,key, \
+				webnotes.conn.get_value('Support Email Settings',None,field_map[key]))
+
+		# delete support email settings
+		delete_doc('DocType', 'Support Email Settings')
+
+		reload_doc('support','doctype','support_ticket')
+		sql("delete from tabDocField where fieldname='problem_description' and parent='Support Ticket'")
+	elif patch_no == 328:
+		if webnotes.conn.get_value('Control Panel', None, 'account_id') != 'axjanak2011':
+			sql("delete from `tabDocField` where fieldname = 'supplier_status' and parent = 'Supplier'")
+	elif patch_no == 329:
+		reload_doc('utilities', 'doctype', 'rename_tool')
+		reload_doc('utilities', 'doctype', 'bulk_rename_tool')
+	elif patch_no == 330:
+		reload_doc('accounts', 'doctype', 'lease_agreement')
+		reload_doc('accounts', 'doctype', 'lease_installment')
+
+		reload_doc('accounts', 'search_criteria', 'lease_agreement_list')
+		reload_doc('accounts', 'search_criteria', 'lease_monthly_future_installment_inflows')
+		reload_doc('accounts', 'search_criteria', 'lease_overdue_age_wise')
+		reload_doc('accounts', 'search_criteria', 'lease_over_due_list')
+		reload_doc('accounts', 'search_criteria', 'lease_receipts_client_wise')
+		reload_doc('accounts', 'search_criteria', 'lease_receipt_summary_year_to_date')
+		reload_doc('accounts', 'search_criteria', 'lease_yearly_future_installment_inflows')
+
+		reload_doc('accounts', 'Module Def', 'Accounts')
+	elif patch_no == 331:
+		p = get_obj('Patch Util')
+		# permission
+		p.add_permission('Lease Agreement', 'Accounts Manager', 0, read = 1, write=1,submit=1, cancel=1,amend=1)
+		p.add_permission('Lease Agreement', 'Accounts Manager', 1, read = 1)
+	elif patch_no == 332:
+		sql("update `tabDocField` set permlevel=1, hidden = 1 where parent = 'Bulk Rename Tool' and fieldname = 'file_list'")
+	elif patch_no == 333:
+		sql("update `tabDocPerm` set `create`  =1 where role = 'Accounts Manager' and parent = 'Lease Agreement'")
+
+		p = get_obj('Patch Util')
+		p.add_permission('DocType Mapper', 'System Manager', 0, read = 1, write=1, create=1)
+		p.add_permission('Role', 'System Manager', 0, read = 1, write=1, create=1)
+		p.add_permission('Print Format', 'System Manager', 0, read = 1, write=1, create=1)
+	elif patch_no == 334:
+		reload_doc('knowledge_base', 'doctype', 'answer')
+	elif patch_no == 335:
+		for dt in ['Account', 'Cost Center', 'Territory', 'Item Group', 'Customer Group']:
+			sql("update `tabDocField` set fieldtype = 'Link', options = %s where fieldname = 'old_parent' and parent = %s", (dt, dt))
+	elif patch_no == 336:
+		reload_doc('server_tools','page','billing')
+	elif patch_no == 337:
+		item_list = webnotes.conn.sql("""SELECT name, description_html
+									FROM tabItem""")
+		if item_list:
+			for item, html in item_list:
+				if html and "getfile" in html and "acx" in html:
+					ac_id = webnotes.conn.sql("""SELECT value FROM `tabSingles` WHERE doctype='Control Panel' AND field='account_id'""")
+					sp_acx = html.split("acx=")
+					l_acx = len(sp_acx)
+					if l_acx > 1:
+						for i in range(l_acx-1):
+							sp_quot = sp_acx[i+1].split('"')
+							if len(sp_quot) > 1: sp_quot[0] = str(ac_id[0][0])
+							sp_acx[i+1] = '"'.join(sp_quot)
+					html = "acx=".join(sp_acx)
+					webnotes.conn.sql("""UPDATE tabItem SET description_html=%s WHERE name=%s""", (html, item))
+	elif patch_no == 338:
+		# Patch for billing status based on amount
+		# reload so and dn
+		reload_doc('selling','doctype','sales_order')
+		reload_doc('stock','doctype','delivery_note')
+
+		# delete billed_qty field
+		sql("delete from `tabDocField` where fieldname = 'billed_qty' and parent in ('Sales Order Detail', 'Delivery Note Detail')")
+
+		# update billed amt in item table in so and dn
+		sql("""	update `tabSales Order Detail` so
+				set billed_amt = (select sum(amount) from `tabRV Detail` where `so_detail`= so.name and docstatus=1 and parent not like 'old%%'), modified = now()""")
+
+		sql(""" update `tabDelivery Note Detail` dn
+				set billed_amt = (select sum(amount) from `tabRV Detail` where `dn_detail`= dn.name and docstatus=1 and parent not like 'old%%'), modified = now()""")
+
+		# calculate % billed based on item table
+		sql("""	update `tabSales Order` so
+				set per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabSales Order Detail` where parent = so.name), modified = now()""")
+
+		sql("""	update `tabDelivery Note` dn
+				set per_billed = (select sum(if(amount > ifnull(billed_amt, 0), billed_amt, amount))/sum(amount)*100 from `tabDelivery Note Detail` where parent = dn.name), modified = now()""")
+
+		# update billing status based on % billed
+		sql("""update `tabSales Order` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
+				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
+		sql("""update `tabDelivery Note` set billing_status = if(ifnull(per_billed,0) < 0.001, 'Not Billed',
+				if(per_billed >= 99.99, 'Fully Billed', 'Partly Billed'))""")
+
+		# update name of questions page
+		sql("update tabPage set name='questions' where name='Questions'")
+		sql("update tabPage set name='question-view' where name='Question View'")
+	elif patch_no == 339:
+		reload_doc('production','doctype','bill_of_materials')
+	elif patch_no == 340:
+		sql("update `tabDocField` set permlevel = 0 where (fieldname in ('process', 'production_order', 'fg_completed_qty') or label = 'Get Items') and parent = 'Stock Entry'")
+	elif patch_no == 341:
+		reload_doc('stock','doctype','delivery_note')
+		reload_doc('stock','doctype','item')
+		reload_doc('selling','doctype','quotation')
+		reload_doc('stock','Print Format','Delivery Note Packing List Wise')
+
+		if not sql("select format from `tabDocFormat` where name = 'Delivery Note Packing List Wise' and parent = 'Delivery Note'"):
+			from webnotes.model.doc import addchild
+			dt_obj = get_obj('DocType', 'Delivery Note', with_children = 1)
+			ch = addchild(dt_obj.doc, 'formats', 'DocFormat', 1)
+			ch.format = 'Delivery Note Packing List Wise'
+			ch.save(1)
+	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'")
+		reload_doc('stock', 'doctype', 'delivery_note_detail')
+		reload_doc('stock', 'doctype', 'item_customer_detail')
+	elif patch_no == 345:
+		# rerun 343 (merge confict)
+		reload_doc('stock','doctype','item_customer_detail')
+		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:
+		pass
+	elif patch_no == 347:
+		sql("delete from `tabField Mapper Detail` where from_field = to_field and map = 'Yes' and ifnull(checking_operator, '') = ''")
+	elif patch_no == 348:
+		sql("update `tabStock Ledger Entry` set is_cancelled = 'No' where voucher_type = 'Serial No'")
+	elif patch_no == 349:
+		delete_doc('Custom Script', 'Update Series-Server')
+		delete_doc('Custom Script', 'Profile-Client')
+		delete_doc('Custom Script', 'Event-Client')
+		delete_doc('Custom Script', 'File-Server')
+
+		# reload profile with new fields for security
+		delete_doc('DocType', 'Profile')
+		reload_doc('core', 'doctype', 'profile')
+	elif patch_no == 350:
+		reload_doc('stock', 'doctype', 'delivery_note_detail')
+		reload_doc('stock', 'doctype', 'item_customer_detail')
+	elif patch_no == 351:
+		reload_doc('home', 'page', 'dashboard')
+	elif patch_no == 352:
+		reload_doc('stock','doctype','delivery_note')
+		reload_doc('stock','doctype','item')
+		reload_doc('selling','doctype','quotation')
+		reload_doc('stock','Print Format','Delivery Note Packing List Wise')
+
+		if not sql("select format from `tabDocFormat` where name = 'Delivery Note Packing List Wise' and parent = 'Delivery Note'"):
+			from webnotes.model.doc import addchild
+			dt_obj = get_obj('DocType', 'Delivery Note', with_children = 1)
+			ch = addchild(dt_obj.doc, 'formats', 'DocFormat', 1)
+			ch.format = 'Delivery Note Packing List Wise'
+			ch.save(1)
+	elif patch_no == 353:
+		reload_doc('core', 'doctype', 'doctype')
+		sql("update `tabDocType` set default_print_format = 'Standard' where name = 'Delivery Note'")
+	elif patch_no == 354:
+		reload_doc('stock', 'doctype', 'delivery_note')
+		reload_doc('stock', 'doctype', 'delivery_note_detail')
+	elif patch_no == 355:
+		sql("update `tabDocField` set print_hide =1 where fieldname in ('pack_no', 'pack_gross_wt', 'weight_uom', 'pack_nett_wt') and parent = 'Delivery Note Detail'")
+	elif patch_no == 356:
+		sql("update `tabDocField` set print_hide =1 where fieldname = 'print_packing_slip' and parent = 'Delivery Note'")
+	elif patch_no == 357:
+		reload_doc('hr', 'doctype', 'salary_manager')
+	elif patch_no == 358:
+		reload_doc('setup', 'doctype','features_setup')
+		reload_doc('stock','doctype','item')
+		sql("update tabDocField set label='Produced Qty',description='Updated after finished goods are transferred to FG Warehouse through Stock Entry' where parent='Production Order' and fieldname='produced_qty'")
+		rs = sql("select fieldname from tabDocField where parent='Features Setup' and fieldname is not null")
+		from webnotes.model.doc import Document
+		m = Document('Features Setup')
+		for d in rs:
+			m.fields[d[0]] = 1
+		m.save()
+	elif patch_no == 359:
+		reload_doc('hr', 'doctype', 'salary_slip')
+		delete_doc('DocType', 'Salary Control Panel')
+	elif patch_no == 360:
+		sql("delete from `tabDocField` where (fieldname in ('client_string', 'server_code_error', 'server_code_compiled', 'server_code', 'server_code_core', 'client_script', 'client_script_core', 'dt_template', 'change_log') or label = 'Template') and parent = 'DocType'")
+	elif patch_no == 361:
+		sql("update `tabModule Def Item` set doc_name = 'GL Entry' where display_name in ('Lease Agreement List', 'Lease Monthly Future Installment Inflows', 'Lease Overdue Age Wise', 'Lease Overdue List', 'Lease Receipts Client Wise', 'Lease Receipt Summary Month Wise', 'Lease Yearly Future Installment Inflows') and parent = 'Accounts'")
+	elif patch_no == 362:
+		sql("update `tabDocField` set no_copy = 1 where fieldname in ('amended_from', 'amendment_date', 'file_list', 'naming_series', 'status')")
+	elif patch_no == 363:
+		reload_doc('accounts', 'search_criteria', 'voucher_wise_tax_details')
+		reload_doc('accounts', 'Module Def', 'Accounts')
+		mappers = sql("select name, module from `tabDocType Mapper`")
+		for d in mappers:
+			if d[0] and d[1]:
+				reload_doc(d[1].lower(), 'DocType Mapper', d[0])
+	elif patch_no == 364:
+		sql("""delete from `tabField Mapper Detail` 
+			where to_field in ('qty', 'amount', 'export_amount') 
+			and parent in ('Sales Order-Receivable Voucher', 'Delivery Note-Receivable Voucher')
+		""")
+		mappers = sql("select name, module from `tabDocType Mapper`")
+		for d in mappers:
+			if d[0] and d[1]:
+				reload_doc(d[1].lower(), 'DocType Mapper', d[0])
+	elif patch_no == 365:
+		from patches.delivery_billing_status_patch import run_patch
+		run_patch()
+	elif patch_no == 367:
+		bin = sql("select name from tabBin")
+		for b in bin:
+			bobj = get_obj('Bin',b[0])
+			prev_sle = bobj.get_prev_sle(posting_date = '2011-09-01', posting_time = '01:00')
+			bobj.update_item_valuation(posting_date = '2011-09-01', posting_time = '01:00', prev_sle = prev_sle)
+	elif patch_no == 368:
+		from webnotes.utils import nestedset
+		t = [
+			['Account', 'parent_account'], ['Cost Center', 'parent_cost_center'], 
+			['Item Group', 'parent_item_group'], ['Territory', 'parent_territory'],
+			['Customer Group', 'parent_customer_group'], ['Sales Person', 'parent_sales_person']
+		]
+		for d in t:
+			nestedset.rebuild_tree(d[0], d[1])
+	elif patch_no == 369:
+		reload_doc('hr', 'doctype', 'appraisal')
+		reload_doc('hr', 'doctype', 'appraisal_detail')
+	elif patch_no == 370:
+		sql("update `tabDocField` set `hidden` = 0 where fieldname = 'group_or_ledger' and parent = 'Cost Center'")
+	elif patch_no == 371:
+		from webnotes.modules.module_manager import reload_doc
+
+		reload_doc('setup', 'doctype','features_setup')
+		flds = ['page_break', 'projects', 'packing_details', 'discounts', 'brands', 'item_batch_nos', 'after_sales_installations', 'item_searial_nos', 'item_group_in_details', 'exports', 'imports', 'item_advanced', 'sales_extras', 'more_info', 'quality', 'manufacturing', 'pos', 'item_serial_nos']
+
+		for f in flds:
+			val = sql("select value from tabSingles where field = '%s' and doctype = 'Features Setup'" % f)
+			val = val and val[0][0] or 0
+			sql("update `tabSingles` set `value` = %s where `field` = '%s' and doctype = 'Features Setup'" % (val, '__'+f))
+
+		st = "'"+"', '".join(flds)+"'"
+		sql("delete from `tabDocField` where fieldname in (%s) and parent = 'Features Setup'" % st)
+		sql("delete from `tabDefaultValue` where defkey in (%s) and parent = 'Control Panel'" % st)
+
+		get_obj('Features Setup', 'Features Setup').doc.save()
+	elif patch_no == 372:
+		from webnotes.modules.module_manager import reload_doc
+
+		reload_doc('setup', 'doctype','features_setup')
+		flds = ['page_break', 'projects', 'packing_details', 'discounts', 'brands', 'item_batch_nos', 'after_sales_installations', 'item_searial_nos', 'item_group_in_details', 'exports', 'imports', 'item_advanced', 'sales_extras', 'more_info', 'quality', 'manufacturing', 'pos', 'item_serial_nos']
+
+		for f in flds:
+			val = sql("select value from tabSingles where field = '%s' and doctype = 'Features Setup'" % f)
+			val = val and val[0][0] or 0
+			sql("update `tabSingles` set `value` = %s where `field` = '%s' and doctype = 'Features Setup'" % (val, 'fs_'+f))
+
+		st = "'__"+"', '__".join(flds)+"'"
+		
+		sql("delete from `tabDocField` where fieldname in (%s) and parent = 'Features Setup'" % st)
+		sql("delete from `tabDefaultValue` where defkey in (%s) and parent = 'Control Panel'" % st)
+
+		get_obj('Features Setup', 'Features Setup').doc.save()
+	elif patch_no == 373:
+		sql("delete from `tabDocField` where fieldname = 'item_searial_nos' and parent = 'Features Setup'")
+		sql("delete from `tabDefaultValue` where defkey = 'item_searial_nos' and parent = 'Control Panel'")
+	elif patch_no == 374:
+		rs = sql("select fieldname from tabDocField where parent='Features Setup' and fieldname is not null")
+		from webnotes.model.code import get_obj
+		m = get_obj('Features Setup')
+		for d in rs:
+			m.doc.fields[d[0]] = 1
+		m.doc.save()
+		m.validate()
+	elif patch_no == 375:
+		from webnotes.session_cache import clear_cache
+		clear_cache(webnotes.session['user'])
+	elif patch_no == 376:
+		reload_doc('stock', 'DocType Mapper', 'Purchase Order-Purchase Receipt')
+	elif patch_no == 377:
+		flds = ['page_break', 'projects', 'packing_details', 'discounts', 'brands', 'item_batch_nos', 'after_sales_installations', 'item_searial_nos', 'item_group_in_details', 'exports', 'imports', 'item_advanced', 'sales_extras', 'more_info', 'quality', 'manufacturing', 'pos', 'item_serial_nos']
+		
+		st = "'"+"', '".join(flds)+"'"
+		sql("delete from `tabDocField` where fieldname in (%s) and parent = 'Features Setup'" % st)
+		sql("delete from `tabDefaultValue` where defkey in (%s) and parent = 'Control Panel'" % st)
+		
+		from webnotes.session_cache import clear_cache
+		clear_cache(webnotes.session['user'])
+	elif patch_no == 378:
+		comp = sql("select name from tabCompany where docstatus!=2")
+		fy = sql("select name from `tabFiscal Year` order by year_start_date asc")
+		for c in comp:
+			prev_fy = ''
+			for f in fy:
+				fy_obj = get_obj('Fiscal Year', f[0])
+				fy_obj.doc.past_year = prev_fy
+				fy_obj.doc.company = c[0]
+				fy_obj.doc.save()
+				fy_obj.repost()
+				prev_fy = f[0]
+				sql("commit")
+				sql("start transaction")
+	elif patch_no == 379:
+		sql("update tabDocPerm set amend = 0 where parent = 'Salary Structure'")
+		sql("update tabDocPerm set cancel = 1 where parent = 'Company' and role = 'System Manager'")
+	elif patch_no == 380:
+		if sql("select count(name) from `tabDocField` where label = 'View Ledger Entry' and parent = 'Journal Voucher' and fieldtype = 'Button'")[0][0] > 1:
+			sql("delete from `tabDocField` where label = 'View Ledger Entry' and parent = 'Journal Voucher' and fieldtype = 'Button' limit 1")
+		if sql("select count(name) from `tabDocField` where label = 'Get Balance' and parent = 'Journal Voucher' and fieldtype = 'Button'")[0][0] > 1:
+			sql("delete from `tabDocField` where label = 'Get Balance' and parent = 'Journal Voucher' and fieldtype = 'Button' limit 1")
+	elif patch_no == 381:
+		reload_doc('accounts', 'doctype', 'internal_reconciliation')
+		reload_doc('accounts', 'doctype', 'ir_payment_detail')
+		reload_doc('accounts', 'Module Def', 'Accounts')
+	elif patch_no == 382:
+		if sql("select count(name) from `tabDocField` where label = 'Get Specification Details' and parent = 'QA Inspection Report' and fieldtype = 'Button'")[0][0] > 1:
+			sql("delete from `tabDocField` where label = 'Get Specification Details' and parent = 'QA Inspection Report' and fieldtype = 'Button' limit 1")
+	elif patch_no == 383:
+		reload_doc('accounts', 'doctype', 'cost_center')
+	elif patch_no == 384:
+		reload_doc('stock', 'Module Def', 'Stock')
+		sql("delete from `tabModule Def Item` where display_name = 'Serial No' and parent = 'Support'")
+		sql("update `tabDocType` set subject = 'Item Code: %(item_code)s, Warehouse: %(warehouse)s' where name = 'Serial No'")
+	elif patch_no == 385:
+		# Patch for adding packing related columns (packed by, checked by, shipping mark etc)
+		reload_doc('stock','doctype','delivery_note')