permission engine fix - is doctype submittable
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/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/permission_control/permission_control.py b/erpnext/setup/doctype/permission_control/permission_control.py
index e21ac84..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
 	# ------------------
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/version.num b/version.num
index a637eba..fbee9e3 100644
--- a/version.num
+++ b/version.num
@@ -1 +1 @@
-980
\ No newline at end of file
+982
\ No newline at end of file