Merge branch 'handlerupdate' into sync_handler_merge

Conflicts:
	js/all-app.js
	version.num
diff --git a/erpnext/home/doctype/company_control/company_control.py b/erpnext/home/doctype/company_control/company_control.py
index 63f8b71..567f9f6 100644
--- a/erpnext/home/doctype/company_control/company_control.py
+++ b/erpnext/home/doctype/company_control/company_control.py
@@ -71,7 +71,10 @@
 			pr.save(1)
 		
 		# Update Membership Type at Gateway
-		if cint(webnotes.conn.get_value('Control Panel', None, 'sync_with_gateway')):
+		import webnotes.defs
+		from webnotes.utils import cint
+		if hasattr(webnotes.defs, 'sync_with_gateway') and \
+				cint(webnotes.defs.sync_with_gateway) or 0:		
 			if 'System Manager' in role_list : membership_type = 'Administrator'
 			else : membership_type = 'Member'
 
diff --git a/erpnext/home/page/my_company/my_company.py b/erpnext/home/page/my_company/my_company.py
index d3a7bc7..f2a2522 100644
--- a/erpnext/home/page/my_company/my_company.py
+++ b/erpnext/home/page/my_company/my_company.py
@@ -54,7 +54,10 @@
 	args = json.loads(args)
 	webnotes.conn.sql("update tabProfile set enabled=0, docstatus=2 where name=%s", args['user'])
 	# erpnext-saas
-	if cint(webnotes.conn.get_value('Control Panel', None, 'sync_with_gateway')):
+	import webnotes.defs
+	from webnotes.utils import cint
+	if hasattr(webnotes.defs, 'sync_with_gateway') and \
+			cint(webnotes.defs.sync_with_gateway) or 0:	
 		from server_tools.gateway_utils import remove_user_gateway
 		remove_user_gateway(args['user'])
 	
@@ -65,7 +68,10 @@
 def add_user(args):
 	args = json.loads(args)
 	# erpnext-saas
-	if cint(webnotes.conn.get_value('Control Panel', None, 'sync_with_gateway')):
+	import webnotes.defs
+	from webnotes.utils import cint
+	if hasattr(webnotes.defs, 'sync_with_gateway') and \
+			cint(webnotes.defs.sync_with_gateway) or 0:
 		from server_tools.gateway_utils import add_user_gateway
 		add_user_gateway(args)
 	
@@ -183,7 +189,10 @@
 	webnotes.conn.set_value('Profile', args['user'], 'login_before', args.get('login_before'))
 
 	if 'new_password' in args:
-		if cint(webnotes.conn.get_value('Control Panel',None,'sync_with_gateway')):
+		import webnotes.defs
+		from webnotes.utils import cint
+		if hasattr(webnotes.defs, 'sync_with_gateway') and \
+				cint(webnotes.defs.sync_with_gateway) or 0:			
 			import server_tools.gateway_utils
 			res = server_tools.gateway_utils.change_password('', args['new_password'], args['user'], args['sys_admin_pwd'])
 			if 'Traceback' not in res['message']:
diff --git a/erpnext/home/page/profile_settings/profile_settings.py b/erpnext/home/page/profile_settings/profile_settings.py
index fb633fd..9b9f890 100644
--- a/erpnext/home/page/profile_settings/profile_settings.py
+++ b/erpnext/home/page/profile_settings/profile_settings.py
@@ -27,8 +27,11 @@
 	
 	if not webnotes.conn.sql('select name from tabProfile where name=%s and password=password(%s)', (webnotes.session['user'], arg['old_password'])):
 		webnotes.msgprint('Old password is not correct', raise_exception=1)
-			
-	if cint(webnotes.conn.get_value('Control Panel',None,'sync_with_gateway')):
+	
+	import webnotes.defs
+	from webnotes.utils import cint
+	if hasattr(webnotes.defs, 'sync_with_gateway') and \
+			cint(webnotes.defs.sync_with_gateway) or 0:	
 		import server_tools.gateway_utils
 		webnotes.msgprint(server_tools.gateway_utils.change_password(arg['old_password'], arg['new_password'])['message'])
 
diff --git a/erpnext/patches/mar_2012/clean_property_setter.py b/erpnext/patches/mar_2012/clean_property_setter.py
new file mode 100644
index 0000000..12e0a9e
--- /dev/null
+++ b/erpnext/patches/mar_2012/clean_property_setter.py
@@ -0,0 +1,52 @@
+import webnotes
+
+def execute():
+	"""
+		* Remove unnecessary doctype properties
+		* Remove docfield property setters if fieldname doesn't exist
+		* Remove prev_field properties if value fieldname doesn't exist
+	"""
+	clean_doctype_properties()
+	clean_docfield_properties()
+
+def clean_doctype_properties():
+	desc = webnotes.conn.sql("DESC `tabDocType`", as_dict=1)
+	property_list = '", "'.join([d.get('Field') for d in desc])
+	webnotes.conn.sql("""\
+		DELETE FROM `tabProperty Setter`
+		WHERE doctype_or_field = 'DocType'
+		AND property NOT IN ("%s")""" % property_list)
+	
+def clean_docfield_properties():
+	delete_list_1 = webnotes.conn.sql("""\
+		SELECT name FROM `tabProperty Setter` ps
+		WHERE doctype_or_field = 'DocField'
+		AND NOT EXISTS (
+			SELECT fieldname FROM `tabDocField` df
+			WHERE df.parent = ps.doc_type
+			AND df.fieldname = ps.field_name
+		) AND NOT EXISTS (
+			SELECT fieldname FROM `tabCustom Field` cf
+			WHERE cf.dt = ps.doc_type
+			AND cf.fieldname = ps.field_name
+		)""")
+	
+	delete_list_2 = webnotes.conn.sql("""\
+		SELECT name FROM `tabProperty Setter` ps
+		WHERE doctype_or_field = 'DocField'
+		AND property = 'previous_field'
+		AND NOT EXISTS (
+			SELECT fieldname FROM `tabDocField` df
+			WHERE df.parent = ps.doc_type
+			AND df.fieldname = ps.value
+		) AND NOT EXISTS (
+			SELECT fieldname FROM `tabCustom Field` cf
+			WHERE cf.dt = ps.doc_type
+			AND cf.fieldname = ps.value
+		)""")
+
+	delete_list = [d[0] for d in delete_list_1] + [d[0] for d in delete_list_2]
+
+	webnotes.conn.sql("""\
+		DELETE FROM `tabProperty Setter`
+		WHERE NAME IN ("%s")""" % '", "'.join(delete_list))
diff --git a/erpnext/patches/mar_2012/cleanup_control_panel.py b/erpnext/patches/mar_2012/cleanup_control_panel.py
new file mode 100644
index 0000000..f26db15
--- /dev/null
+++ b/erpnext/patches/mar_2012/cleanup_control_panel.py
@@ -0,0 +1,7 @@
+import webnotes
+def execute():
+	webnotes.conn.sql("""\
+		DELETE FROM `tabSingles`
+		WHERE doctype = 'Control Panel'
+		AND field IN ("sync_with_gateway", "mail_password", "auto_email_id",
+		"mail_port", "outgoing_mail_server", "mail_login", "use_ssl")""")
diff --git a/erpnext/patches/mar_2012/doctype_get_refactor.py b/erpnext/patches/mar_2012/doctype_get_refactor.py
new file mode 100644
index 0000000..9818f7c
--- /dev/null
+++ b/erpnext/patches/mar_2012/doctype_get_refactor.py
@@ -0,0 +1,161 @@
+import webnotes
+def execute():
+	"""
+		* Custom Field changes
+		* Add file_list to required tables
+		* Change floats/currency to decimal(14, 6)
+		* Remove DocFormat from DocType's fields
+		* Remove 'no_column' from DocField
+		* Drop table DocFormat
+	"""
+	change_property_setter_fieldnames()
+	handle_custom_fields()
+	create_file_list()
+
+	# do at last - needs commit due to DDL statements
+	change_to_decimal()
+
+def change_property_setter_fieldnames():
+	docfield_list = webnotes.conn.sql("""\
+		SELECT name, fieldname FROM `tabDocField`""", as_list=1)
+	custom_field_list = webnotes.conn.sql("""\
+		SELECT name, fieldname FROM `tabCustom Field`""", as_list=1)
+	field_list = docfield_list + custom_field_list
+	property_setter_list = webnotes.conn.sql("""\
+		SELECT name, doc_name, value, property
+		FROM `tabProperty Setter`
+		WHERE doctype_or_field='DocField'""")
+	field_dict = dict(field_list)
+	for name, doc_name, value, prop in property_setter_list:
+		if doc_name in field_dict:
+			webnotes.conn.sql("""\
+				UPDATE `tabProperty Setter`
+				SET field_name = %s
+				WHERE name = %s""", (field_dict.get(doc_name), name))
+		if value in field_dict and prop=='previous_field':
+			webnotes.conn.sql("""\
+				UPDATE `tabProperty Setter`
+				SET value = %s
+				WHERE name = %s""", (field_dict.get(value), name))
+
+
+def handle_custom_fields():
+	"""
+		* Assign idx to custom fields
+		* Create property setter entry of previous field
+		* Remove custom fields from tabDocField
+	"""
+	cf = get_cf()
+	assign_idx(cf)
+	create_prev_field_prop_setter(cf)
+	remove_custom_from_docfield(cf)
+
+def get_cf():
+	return webnotes.conn.sql("""\
+		SELECT * FROM `tabCustom Field`
+		WHERE docstatus < 2""", as_dict=1)
+
+def assign_idx(cf):
+	from webnotes.model.doctype import get
+	from webnotes.utils import cint
+	for f in cf:
+		if f.get('idx'): continue
+		temp_doclist = get(f.get('dt'), form=0)
+		max_idx = max(d.idx for d in temp_doclist if d.doctype=='DocField')
+		if not max_idx: continue
+		webnotes.conn.sql("""\
+			UPDATE `tabCustom Field` SET idx=%s
+			WHERE name=%s""", (cint(max_idx)+1, f.get('name')))
+
+def create_prev_field_prop_setter(cf):
+	from webnotes.model.doc import Document
+	from core.doctype.custom_field.custom_field import get_fields_label
+	for f in cf:
+		idx_label_list, field_list = get_fields_label(f.get('dt'), 0)
+		temp_insert_after = (f.get('insert_after') or '').split(" - ")
+		if len(temp_insert_after)<=1: continue
+		similar_idx_label = [il for il in idx_label_list \
+			if temp_insert_after[0] in il]
+		if not similar_idx_label: continue
+		label_index = idx_label_list.index(similar_idx_label[0])
+		if label_index==-1: return
+
+		webnotes.conn.sql("""\
+			UPDATE `tabCustom Field`
+			SET insert_after = %s
+			WHERE name = %s""", (similar_idx_label[0], f.get('name')))
+
+		prev_field = field_list[label_index]
+		webnotes.conn.sql("""\
+			DELETE FROM `tabProperty Setter`
+			WHERE doc_type = %s
+			AND field_name = %s
+			AND property = 'previous_field'""", (f.get('dt'), f.get('fieldname')))
+
+		ps = Document('Property Setter', fielddata = {
+			'doctype_or_field': 'DocField',
+			'doc_type': f.get('dt'),
+			'field_name': f.get('fieldname'),
+			'property': 'previous_field',
+			'value': prev_field,
+			'property_type': 'Data',
+			'select_doctype': f.get('dt')
+		})
+		ps.save(1)
+
+def remove_custom_from_docfield(cf):
+	for f in cf:
+		webnotes.conn.sql("""\
+			DELETE FROM `tabDocField`
+			WHERE parent=%s AND fieldname=%s""", (f.get('dt'),
+			f.get('fieldname')))
+
+def create_file_list():
+	should_exist = ['Website Settings', 'Web Page', 'Timesheet', 'Ticket',
+		'Support Ticket', 'Supplier', 'Style Settings', 'Stock Reconciliation',
+		'Stock Entry', 'Serial No', 'Sales Order', 'Receivable Voucher',
+		'Quotation', 'Question', 'Purchase Receipt', 'Purchase Order',
+		'Project', 'Profile', 'Production Order', 'Product', 'Print Format',
+		'Price List', 'Payable Voucher', 'Page', 'Module Def',
+		'Maintenance Visit', 'Maintenance Schedule', 'Letter Head',
+		'Leave Application', 'Lead', 'Journal Voucher', 'Item', 'Indent',
+		'Expense Voucher', 'Enquiry', 'Employee', 'Delivery Note',
+		'Customer Issue', 'Customer', 'Contact Us Settings', 'Company',
+		'Bulk Rename Tool', 'Blog', 'Bill Of Materials', 'About Us Settings']
+
+	from webnotes.model.code import get_obj
+
+	for dt in should_exist:
+		obj = get_obj('DocType', dt, with_children=1)
+		obj.doc.allow_attach = 1
+		obj.doc.save()
+		obj.make_file_list()
+		from webnotes.model.db_schema import updatedb
+		updatedb(obj.doc.name)
+		from webnotes.utils.cache import CacheItem
+		CacheItem(obj.doc.name).clear()
+
+def change_to_decimal():
+	webnotes.conn.commit()
+	tables = webnotes.conn.sql("SHOW TABLES")
+	alter_tables_list = []
+	for tab in tables:
+		if not tab: continue
+		desc = webnotes.conn.sql("DESC `%s`" % tab[0], as_dict=1)
+		flist = []
+		for d in desc:
+			if d.get('Type')=='decimal(14,2)':
+				flist.append(d.get('Field'))
+		if flist:
+			#print tab[0], flist
+			statements = ("MODIFY `%s` decimal(14,6)" % f for f in flist)
+			statements = ", \n".join(statements)
+			alter_tables_list.append("ALTER TABLE `%s` \n%s\n" % (tab[0],
+				statements))
+	
+	#print "\n\n".join(alter_tables_list)
+	for at in alter_tables_list:
+		webnotes.conn.sql(at)
+
+	webnotes.conn.begin()
+
diff --git a/erpnext/patches/mar_2012/is_submittable_patch.py b/erpnext/patches/mar_2012/is_submittable_patch.py
new file mode 100644
index 0000000..d49160c
--- /dev/null
+++ b/erpnext/patches/mar_2012/is_submittable_patch.py
@@ -0,0 +1,23 @@
+# dont run this patch
+def execute():
+	import webnotes
+	import webnotes.model.doctype
+	from webnotes.utils import cint
+	from webnotes.model.doc import Document
+	from webnotes.model.code import get_obj
+	doctype_list = webnotes.conn.sql("SELECT name FROM `tabDocType`")
+	for dt in doctype_list:
+		doclist = webnotes.model.doctype.get(dt[0], form=0)
+		is_submittable = 0
+		for d in doclist:
+			if d.doctype == 'DocPerm' and d.fields.get('permlevel') == 0 \
+				and cint(d.fields.get('submit')) == 1:
+					is_submittable = 1
+					break
+		if is_submittable:
+			dt_doc = Document('DocType', doclist[0].name)
+			dt_doc.is_submittable = 1
+			dt_doc.save()
+			obj = get_obj(doc=dt_doc)
+			obj.make_amendable()
+			obj.on_update()
diff --git a/erpnext/setup/doctype/email_settings/email_settings.js b/erpnext/setup/doctype/email_settings/email_settings.js
deleted file mode 100644
index 599fbcc..0000000
--- a/erpnext/setup/doctype/email_settings/email_settings.js
+++ /dev/null
@@ -1,21 +0,0 @@
-// ERPNext - web based ERP (http://erpnext.com)
-// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
-// 
-// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-// 
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-// 
-// You should have received a copy of the GNU General Public License
-// along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-cur_frm.cscript.refresh = function(doc,cdt,cdn){
-  if(!doc.outgoing_mail_server || !doc.mail_login || !doc.mail_password || !doc.auto_email_id || !doc.mail_port || !doc.use_ssl){
-    get_server_fields('set_vals','','',doc, cdt, cdn, 1);
-  }
-}
\ No newline at end of file
diff --git a/erpnext/setup/doctype/email_settings/email_settings.py b/erpnext/setup/doctype/email_settings/email_settings.py
index c670b31..3e17636 100644
--- a/erpnext/setup/doctype/email_settings/email_settings.py
+++ b/erpnext/setup/doctype/email_settings/email_settings.py
@@ -23,21 +23,6 @@
 	def __init__(self,doc,doclist):
 		self.doc,self.doclist = doc,doclist
 
-	def set_vals(self):
-		res = sql("select field, value from `tabSingles` where doctype = 'Control Panel' and field IN ('outgoing_mail_server','mail_login','mail_password','auto_email_id','mail_port','use_ssl')")
-		ret = {}
-		for r in res:
-			ret[cstr(r[0])]=r[1] and cstr(r[1]) or ''
-				
-		return ret
-
-	def set_cp_value(self, key):
-		"""
-			Update value in control panel
-		"""
-		webnotes.conn.set_value('Control Panel', None, key,
-				self.doc.fields.get(key))
-
 	def validate(self):
 		"""
 			Checks connectivity to email servers before saving
@@ -113,11 +98,3 @@
 			except poplib.error_proto, e:
 				webnotes.msgprint('Invalid User Name or Support Password. Please rectify and try again.')
 				webnotes.msgprint(e)
-
-		
-	def on_update(self):
-		"""
-			update control panel
-		"""
-		for f in ('outgoing_mail_server', 'mail_login', 'mail_password', 'auto_email_id', 'mail_port', 'use_ssl'):
-			self.set_cp_value(f)
diff --git a/erpnext/setup/doctype/permission_control/permission_control.py b/erpnext/setup/doctype/permission_control/permission_control.py
index 049a3f5..d261c41 100644
--- a/erpnext/setup/doctype/permission_control/permission_control.py
+++ b/erpnext/setup/doctype/permission_control/permission_control.py
@@ -57,22 +57,31 @@
 	# Get Perm Level, Perm type of Doctypes of Module and Role Selected
 	# -------------------------------------------------------------------
 	def get_permissions(self,doctype):
-		ret = []
-			
-		# Get permtype for the role selected
-		ptype = sql("select `role`,`permlevel`,`read`,`write`,`create`,`submit`,`cancel`,`amend` from tabDocPerm where `parent` = %s order by `permlevel` ASC",doctype,as_dict = 1)
+		import webnotes.model.doctype
+		doclist = webnotes.model.doctype.get(doctype, form=0)
+		
+		ptype = [{
+				'role': perm.role,
+				'permlevel': cint(perm.permlevel),
+				'read': cint(perm.read),
+				'write': cint(perm.write),
+				'create': cint(perm.create),
+				'cancel': cint(perm.cancel),
+				'submit': cint(perm.submit),
+				'amend': cint(perm.amend)
+				} for perm in sorted(doclist,
+					key=lambda d: [d.fields.get('permlevel'),
+						d.fields.get('role')]) if perm.doctype=='DocPerm']
 
-		# to convert 0L in 0 in values of dictionary
-		for p in ptype:
-			for key in p:
-				if key!='role':
-					p[key] = cint(p[key])
-			ret.append(p)
-						
-		# fields list
-		fl = ['', 'owner'] + [l[0] for l in sql("select fieldname from tabDocField where parent=%s and fieldtype='Link' and ifnull(options,'')!=''", doctype)]
-						
-		return {'perms':ret, 'fields':fl}
+		fl = ['', 'owner'] + [d.fieldname for d in doclist \
+				if d.doctype=='DocField' and d.fieldtype=='Link' \
+				and cstr(d.options)!='']
+
+		return {
+			'perms':ptype,
+			'fields':fl,
+			'is_submittable': doclist[0].fields.get('is_submittable')
+		}
 		
 	# get default values
 	# ------------------
@@ -180,6 +189,11 @@
 							sql("delete from tabDocPerm where parent = %s and role = %s and ifnull(permlevel,0) = %s",(parent, role, cint(permlevel)))
 						
 						sql("update tabDocType set modified = %s where name = %s",(now(), parent))
+
+
+		from webnotes.utils.cache import CacheItem
+		CacheItem(parent).clear()		
+
 		msgprint("Permissions Updated")
 				
 	# Get Fields based on DocType and Permlevel
diff --git a/erpnext/setup/page/permission_engine/permission_engine.js b/erpnext/setup/page/permission_engine/permission_engine.js
index 1d77e51..5f5630c 100644
--- a/erpnext/setup/page/permission_engine/permission_engine.js
+++ b/erpnext/setup/page/permission_engine/permission_engine.js
@@ -148,9 +148,13 @@
 		 // Get permissions
 		if(r.message.perms.length) {
 			me.get_results(r.message);
+			pscript.is_submittable = cint(r.message.is_submittable);
 		}
-		else me.body.innerHTML = '<div style = "color : red; margin:8px 0px;">No Records Found</div>'
-		pscript.show_submittable();
+		else {
+			me.body.innerHTML = '<div style = "color : red; margin:8px 0px;">No Records Found</div>'
+			pscript.is_submittable = 0;
+		}
+		pscript.hide_submit_amend()
 	});
 }
 
@@ -171,6 +175,7 @@
 	
 	var head = $a(this.body, 'h3'); head.innerHTML = 'Rules for ' + doctype;				
 	var permt = make_table(me.body, perms.length+1,9,'80%',[],{border:'1px solid #AAA', padding:'3px', verticalAlign:'middle', height:'30px'});
+	$(permt).attr('id', 'perm_table');
 		
 	// Create Grid for particular DocType
 	// ------------------------------------
@@ -203,9 +208,7 @@
 			var val = perms[l][$td(permt,0,m+2).fieldname];
 			if(val == 1) chk.checked = 1;
 			else chk.checked = 0;
-
-			if(m==3) { chk.onclick = pscript.show_submittable }
-
+			//if(m==3) { chk.onclick = pscript.show_submittable }
 			chk.doctype = doctype;
 			chk.permlevel = perms[l].permlevel; chk.perm_type = col_labels[m+2].toLowerCase(); chk.role = perms[l].role;
 			pscript.all_checkboxes.push(chk);
@@ -214,21 +217,18 @@
 	
 	// add selects for match
 	me.add_match_select(r, perms, permt, doctype);
+
 }
 
-// Show submittable warning
-pscript.show_submittable = function() {
-	var submittable = 0;
-	for(i in pscript.all_checkboxes) {
-		c = pscript.all_checkboxes[i];
-		if(c.perm_type=='submit' && c.checked) {
-			submittable = 1;
-			break;
-		}
-	}
-	if(submittable) {
+pscript.hide_submit_amend = function() {
+	var perm_table = $('#perm_table');
+	if (pscript.is_submittable) {
+		perm_table.find('td:nth-child(6)').each(function() { $(this).toggle(true); });
+		perm_table.find('td:nth-child(8)').each(function() { $(this).toggle(true); });
 		$('#submittable_warning').toggle(true);
 	} else {
+		perm_table.find('td:nth-child(6)').each(function() { $(this).toggle(false); });
+		perm_table.find('td:nth-child(8)').each(function() { $(this).toggle(false); });
 		$('#submittable_warning').toggle(false);
 	}
 }
@@ -538,6 +538,22 @@
 		if(sel_val(s))
 			add_to_out(s.details.parent, s.details.permlevel, s.details.role, 'match', sel_val(s));
 	}
+
+	if(pscript.is_submittable) {
+		var doctype = sel_val(me.type_select);
+		var validated = false;
+		for(var role in out[doctype][0]) {
+			if(out[doctype][0][role]['submit']) {
+				validated = true;
+				break;
+			};
+		}
+		if(!validated) {
+			msgprint("Atleast one Role at Level 0 needs to have submit permission. \
+					 Please rectify and try again.")
+			return;
+		}
+	}
 	
 	var args = "{'perm_dict': "+JSON.stringify(out)+"}"
 	$c_obj('Permission Control','update_permissions', args, function(r,rt) {});
diff --git a/erpnext/startup/event_handlers.py b/erpnext/startup/event_handlers.py
index 703399a..e5846b5 100644
--- a/erpnext/startup/event_handlers.py
+++ b/erpnext/startup/event_handlers.py
@@ -26,9 +26,11 @@
 	if login_manager.user not in ('Guest', None, '') and webnotes.conn.cur_db_name!='accounts' and webnotes.conn.get_value('Control Panel', 'Control Panel', 'account_id')!='s5u011':
 		try:
 			login_manager = login_as(login_manager)
-			update_account_details()
-			import server_tools.gateway_utils
-			server_tools.gateway_utils.check_login(login_manager.user)
+			if hasattr(webnotes.defs, 'sync_with_gateway') and \
+					cint(webnotes.defs.sync_with_gateway) or 0:
+				update_account_details()
+				import server_tools.gateway_utils
+				server_tools.gateway_utils.check_login(login_manager.user)
 			
 		except ImportError:
 			pass
@@ -158,6 +160,8 @@
 # logout the user from SSO
 #
 def on_logout(login_manager):
-	if cint(webnotes.conn.get_value('Control Panel', None, 'sync_with_gateway')):
+	import webnotes.defs
+	if hasattr(webnotes.defs, 'sync_with_gateway') and \
+			cint(webnotes.defs.sync_with_gateway) or 0:
 		from server_tools.gateway_utils import logout_sso
 		logout_sso(user=login_manager.user)
diff --git a/erpnext/utilities/page/users/users.js b/erpnext/utilities/page/users/users.js
index 9ce622e..ad238ae 100644
--- a/erpnext/utilities/page/users/users.js
+++ b/erpnext/utilities/page/users/users.js
@@ -232,7 +232,7 @@
 				$c_page('utilities', 'users', 'add_user', v, function(r,rt) {
 					if(r.exc) { msgprint(r.exc); return; }
 					else {
-						wn.boot.user_info[v.user] = {fullname:v.first_name + ' ' + v.last_name};
+						wn.boot.user_info[v.user] = {fullname:v.first_name + ' ' + (v.last_name || '')};
 						d.hide();
 						me.refresh();
 					}
diff --git a/erpnext/utilities/page/users/users.py b/erpnext/utilities/page/users/users.py
index f2bb1a5..ec01479 100644
--- a/erpnext/utilities/page/users/users.py
+++ b/erpnext/utilities/page/users/users.py
@@ -83,7 +83,10 @@
 	webnotes.conn.set_value('Profile', args['user'], 'enabled', int(args.get('enabled',0)) or 0)
 
 	if args.get('new_password') and args.get('sys_admin_pwd'):
-		if cint(webnotes.conn.get_value('Control Panel',None,'sync_with_gateway')):
+		import webnotes.defs
+		from webnotes.utils import cint
+		if hasattr(webnotes.defs, 'sync_with_gateway') and \
+				cint(webnotes.defs.sync_with_gateway) or 0:
 			import server_tools.gateway_utils
 			res = server_tools.gateway_utils.change_password('', args['new_password'], 
 				args['user'], args['sys_admin_pwd'])
@@ -104,7 +107,10 @@
 def add_user(args):
 	args = json.loads(args)
 	# erpnext-saas
-	if cint(webnotes.conn.get_value('Control Panel', None, 'sync_with_gateway')):
+	import webnotes.defs
+	from webnotes.utils import cint
+	if hasattr(webnotes.defs, 'sync_with_gateway') and \
+			cint(webnotes.defs.sync_with_gateway) or 0:	
 		from server_tools.gateway_utils import add_user_gateway
 		add_user_gateway(args)
 	
@@ -169,7 +175,10 @@
 	webnotes.conn.sql("update tabProfile set enabled=0, docstatus=2 where name=%s", 
 		webnotes.form_dict['uid'])
 	# erpnext-saas
-	if int(webnotes.conn.get_value('Control Panel', None, 'sync_with_gateway')):
+	import webnotes.defs
+	from webnotes.utils import cint
+	if hasattr(webnotes.defs, 'sync_with_gateway') and \
+			cint(webnotes.defs.sync_with_gateway) or 0:
 		from server_tools.gateway_utils import remove_user_gateway
 		remove_user_gateway(webnotes.form_dict['uid'])
 
diff --git a/js/all-app.js b/js/all-app.js
index f83f479..925611a 100644
--- a/js/all-app.js
+++ b/js/all-app.js
@@ -1668,8 +1668,8 @@
 this.meta.section_style='Simple';this.layout=new Layout(this.page_layout.body,'100%');if(this.meta.in_dialog){$(this.page_layout.wrapper).removeClass('layout-wrapper-background');$(this.page_layout.main).removeClass('layout-main-section');$(this.page_layout.sidebar_area).toggle(false);}else{this.setup_sidebar();}
 this.setup_footer();if(!(this.meta.istable||user=='Guest'))this.frm_head=new _f.FrmHeader(this.page_layout.head,this);if(this.frm_head&&this.meta.in_dialog)$dh(this.frm_head.page_head.close_btn);if(this.meta.colour)
 this.layout.wrapper.style.backgroundColor='#'+this.meta.colour.split(':')[1];this.setup_fields_std();}
-_f.Frm.prototype.setup_print=function(){var fl=getchildren('DocFormat',this.meta.name,'formats','DocType');var l=[];this.default_format='Standard';if(fl.length){this.default_format=fl[0].format;for(var i=0;i<fl.length;i++)
-l.push(fl[i].format);}
+_f.Frm.prototype.setup_print=function(){var l=[]
+this.default_format='Standard';for(var key in locals['Print Format']){if(locals['Print Format'][key].doc_type==this.meta.name){l.push(locals['Print Format'][key].name);}}
 if(this.meta.default_print_format)
 this.default_format=this.meta.default_print_format;l.push('Standard');this.print_sel=$a(null,'select','',{width:'160px'});add_sel_options(this.print_sel,l);this.print_sel.value=this.default_format;}
 _f.Frm.prototype.print_doc=function(){if(this.doc.docstatus==2){msgprint("Cannot Print Cancelled Documents.");return;}
diff --git a/version.num b/version.num
index 669268d..a8d5481 100644
--- a/version.num
+++ b/version.num
@@ -1 +1 @@
-1395
\ No newline at end of file
+1396
\ No newline at end of file
diff --git a/wnf.py b/wnf.py
index ca780cf..0a4ff4b 100755
--- a/wnf.py
+++ b/wnf.py
@@ -78,9 +78,7 @@
 	# install
 	parser.add_option('--install', nargs=3, metavar = "rootpassword dbname source",
 						help="install fresh db")
-	parser.add_option('--sync_with_gateway', nargs=1, metavar = "1/0", \
-						help="Set or Unset Sync with Gateway")
-
+	
 	# diff
 	parser.add_option('--diff_ref_file', nargs=0, \
 						help="Get missing database records and mismatch properties, with file as reference")
@@ -185,17 +183,6 @@
 		inst.import_from_db(options.install[1], source_path=options.install[2], \
 			password='admin', verbose = 1)
 	
-	elif options.sync_with_gateway:
-		if int(options.sync_with_gateway[0]) in [0, 1]:
-			webnotes.conn.begin()
-			webnotes.conn.sql("""\
-				UPDATE `tabSingles` SET value=%s
-				WHERE field='sync_with_gateway' AND doctype='Control Panel'""", int(options.sync_with_gateway[0]))
-			webnotes.conn.commit()
-			webnotes.message_log.append("sync_with_gateway set to %s" % options.sync_with_gateway[0])
-		else:
-			webnotes.message_log.append("ERROR: sync_with_gateway can be either 0 or 1")
-	
 	elif options.diff_ref_file is not None:
 		import webnotes.modules.diff
 		webnotes.modules.diff.diff_ref_file()