price list cleanup
diff --git a/erpnext/accounts/doctype/account/account.js b/erpnext/accounts/doctype/account/account.js
index 162eeaf..75cc9e5 100644
--- a/erpnext/accounts/doctype/account/account.js
+++ b/erpnext/accounts/doctype/account/account.js
@@ -30,12 +30,12 @@
 // Refresh
 // -----------------------------------------
 cur_frm.cscript.refresh = function(doc, cdt, cdn) {
+	cur_frm.toggle_fields('account_name', doc.__islocal);
+	
 	// hide fields if group
 	cur_frm.toggle_fields(['account_type', 'master_type', 'master_name', 'freeze_account', 
 		'credit_days', 'credit_limit', 'tax_rate'], doc.group_or_ledger=='Ledger')	
 
-	cur_frm.toggle_fields('account_name', doc.__islocal)
-
 	// read-only for root accounts
   	root_acc = ['Application of Funds (Assets)','Expenses','Income','Source of Funds (Liabilities)'];
 	if(in_list(root_acc, doc.account_name)) {
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.js b/erpnext/accounts/doctype/cost_center/cost_center.js
index 9b66704..c131081 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.js
+++ b/erpnext/accounts/doctype/cost_center/cost_center.js
@@ -34,9 +34,9 @@
 }
 
 cur_frm.cscript.refresh = function(doc, cdt, cdn) {
-	cur_frm.toggle_fields('cost_center_name', doc.__islocal)
-
 	var intro_txt = '';
+	cur_frm.toggle_fields('cost_center_name', doc.__islocal);
+
 	if(!doc.__islocal && doc.group_or_ledger=='Group') {
 		intro_txt += '<p><b>Note:</b> This is Cost Center is a <i>Group</i>, \
 			Accounting Entries are not allowed against groups.</p>';
diff --git a/erpnext/accounts/doctype/fiscal_year/fiscal_year.js b/erpnext/accounts/doctype/fiscal_year/fiscal_year.js
index f263ee4..d60e4ec 100644
--- a/erpnext/accounts/doctype/fiscal_year/fiscal_year.js
+++ b/erpnext/accounts/doctype/fiscal_year/fiscal_year.js
@@ -1,4 +1,3 @@
 cur_frm.cscript.refresh = function(doc, dt, dn) {
-	cur_frm.toggle_fields('year', doc.__islocal);
 	cur_frm.enable_fields('year_start_date', doc.__islocal)
 }
diff --git a/erpnext/setup/doctype/price_list/price_list.js b/erpnext/setup/doctype/price_list/price_list.js
index a222a65..11993f8 100644
--- a/erpnext/setup/doctype/price_list/price_list.js
+++ b/erpnext/setup/doctype/price_list/price_list.js
@@ -14,24 +14,34 @@
 // You should have received a copy of the GNU General Public License
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-
-//--------- ONLOAD -------------
-cur_frm.cscript.onload = function(doc, cdt, cdn) {
-}
-
 cur_frm.cscript.refresh = function(doc, cdt, cdn) {
 	if(doc.__islocal) {
-		set_field_options('price_help', ''); return;
+		cur_frm.set_intro("Save this list to begin.");
+		return;
 	}
 	if(!doc.file_list) {
-		set_field_options('price_help', '<div class="help_box">To upload a price list, please attach a (.csv) file with 3 columns - <b>Item Code, Price and Currency</b> (no headings necessary). See attachments box in the right column</div>')
-	} else {
-		set_field_options('price_help', '<div class="help_box">To update prices from the attachment, please click on "Update Prices"</div>')
-	}
-}
+		cur_frm.set_intro('<p>1. Click on "Download Template" \
+			to download the template of all Items.</p>'
+		+'<p>2. Update prices and Currency.</p>'
+		+'<p>3. Save it as a CSV (.csv) file.</p>'
+		+'<p>4. Upload the file.</p>');
+		
+		cur_frm.add_custom_button('Download Template', function() {
+			$c_obj_csv(cur_frm.get_doclist(), 'download_template');
+		}, 'icon-download')
+		
+		cur_frm.add_custom_button('Upload Price List', function() {
+			cur_frm.attachments.add_attachment();
+		}, 'icon-upload')
+		
 
-cur_frm.cscript.clear_prices = function(doc, cdt, cdn) {
-	if(confirm("This action will clear all rates for '"+ doc.name +"' from the Item Master and cannot be un-done. Are you sure you want to continue?")) {
-		$c_obj(make_doclist(doc.doctype, doc.name), 'clear_prices', '', function(r, rt) { });
+	} else {
+		cur_frm.set_intro('To update prices from the attachment, click on "Update Prices". \
+			To reset prices, delete the attachment (in the sidebar) and upload again.');
+		
+		// Update Prices
+		cur_frm.add_custom_button('Update Prices', function() {
+			cur_frm.call_server('update_prices');
+		}, 'icon-refresh')		
 	}
 }
diff --git a/erpnext/setup/doctype/price_list/price_list.py b/erpnext/setup/doctype/price_list/price_list.py
index be59c65..69b87a5 100644
--- a/erpnext/setup/doctype/price_list/price_list.py
+++ b/erpnext/setup/doctype/price_list/price_list.py
@@ -14,23 +14,10 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-# Please edit this list and import only required elements
 import webnotes
 
-from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
-from webnotes.model import db_exists
-from webnotes.model.doc import Document, addchild, getchildren, make_autoname
-from webnotes.model.doclist import getlist, copy_doclist
-from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
-from webnotes import session, form, is_testing, msgprint, errprint
-
-set = webnotes.conn.set
-sql = webnotes.conn.sql
-get_value = webnotes.conn.get_value
-in_transaction = webnotes.conn.in_transaction
-convert_to_lists = webnotes.conn.convert_to_lists
-	
-# -----------------------------------------------------------------------------------------
+from webnotes.model.doc import Document
+from webnotes import msgprint
 
 
 class DocType:
@@ -43,11 +30,25 @@
 		if currency in self.cl:
 			return 1
 			
-		if sql("select name from tabCurrency where name=%s", currency):
+		if webnotes.conn.sql("select name from tabCurrency where name=%s", currency):
 			self.cl.append(currency)
 			return 1
 		else:
 			return 0
+			
+	def download_template(self, arg=None):
+		"""download 3 column template with all Items"""
+		default_currency = webnotes.conn.get_default('currency')
+		item_list = webnotes.conn.sql("""select name from tabItem where 
+			ifnull(is_stock_item,'')='Yes' and (ifnull(is_sales_item,'')='Yes'
+				or ifnull(is_service_item,'')='Yes')""")
+		data = [self.get_price(i[0], default_currency) for i in item_list]
+		return [['Item', 'Rate', 'Currency']] + data
+	
+	def get_price(self, item, default_currency):
+		rate = webnotes.conn.sql("""select ref_rate, ref_currency from `tabItem Price` 
+			where parent=%s and price_list_name=%s""", (item, self.doc.name))
+		return [item, rate and rate[0][0] or 0, rate and rate[0][1] or default_currency]
 	
 	# update prices in Price List
 	def update_prices(self):
@@ -57,15 +58,15 @@
 		updated = 0
 		
 		for line in data:
-			if line and len(line)==3:
+			if line and len(line)==3 and line[0]!='Item':
 				# if item exists
-				if sql("select name from tabItem where name=%s", line[0]):
+				if webnotes.conn.sql("select name from tabItem where name=%s", line[0]):
 					if self.is_currency_valid(line[2]):
 						# if price exists
-						ref_ret_detail = sql("select name from `tabItem Price` where parent=%s and price_list_name=%s and ref_currency=%s", \
+						ref_ret_detail = webnotes.conn.sql("select name from `tabItem Price` where parent=%s and price_list_name=%s and ref_currency=%s", \
 							(line[0], self.doc.name, line[2]))
 						if ref_ret_detail:
-							sql("update `tabItem Price` set ref_rate=%s where name=%s", (line[1], ref_ret_detail[0][0]))
+							webnotes.conn.sql("update `tabItem Price` set ref_rate=%s where name=%s", (line[1], ref_ret_detail[0][0]))
 						else:
 							d = Document('Item Price')
 							d.parent = line[0]
@@ -80,17 +81,9 @@
 						msgprint("[Ignored] Unknown currency '%s' for Item '%s'" % (line[2], line[0]))
 				else:
 					msgprint("[Ignored] Did not find Item '%s'" % line[1])
-			else:
-				msgprint("[Ignored] Incorrect format: %s" % str(line))
 		
 		msgprint("<b>%s</b> items updated" % updated)
 
-	# clear prices
-	def clear_prices(self):
-		cnt = sql("select count(*) from `tabItem Price` where price_list_name = %s", self.doc.name)
-		sql("delete from `tabItem Price` where price_list_name = %s", self.doc.name)
-		msgprint("%s prices cleared" % cnt[0][0])
-
 	# Update CSV data
 	def get_csv_data(self):
 		if not self.doc.file_list:
@@ -99,8 +92,12 @@
 
 		fid = self.doc.file_list.split(',')[1]
 		  
-		from webnotes.utils import file_manager
-		fn, content = file_manager.get_file(fid)
+		try:
+			from webnotes.utils import file_manager
+			fn, content = file_manager.get_file(fid)
+		except Exception, e:
+			webnotes.msgprint("Unable to open attached file. Please try again.")
+			raise e
 	
 		# NOTE: Don't know why this condition exists
 		if not isinstance(content, basestring) and hasattr(content, 'tostring'):
diff --git a/erpnext/setup/doctype/price_list/price_list.txt b/erpnext/setup/doctype/price_list/price_list.txt
index 2881cd7..4aa3b3b 100644
--- a/erpnext/setup/doctype/price_list/price_list.txt
+++ b/erpnext/setup/doctype/price_list/price_list.txt
@@ -3,9 +3,9 @@
 
 	# These values are common in all dictionaries
 	{
-		'creation': '2012-05-15 12:15:02',
+		'creation': '2012-07-03 13:30:55',
 		'docstatus': 0,
-		'modified': '2012-06-22 10:51:23',
+		'modified': '2012-07-11 17:06:32',
 		'modified_by': u'Administrator',
 		'owner': u'Administrator'
 	},
@@ -14,6 +14,9 @@
 	{
 		'_last_update': u'1303100817',
 		'allow_attach': 1,
+		'allow_copy': 1,
+		'allow_email': 1,
+		'allow_print': 1,
 		'allow_trash': 1,
 		'autoname': u'field:price_list_name',
 		'colour': u'White:FFF',
@@ -34,7 +37,8 @@
 		'name': '__common__',
 		'parent': u'Price List',
 		'parentfield': u'fields',
-		'parenttype': u'DocType'
+		'parenttype': u'DocType',
+		'permlevel': 0
 	},
 
 	# These values are common for all DocPerm
@@ -108,71 +112,20 @@
 	# DocField
 	{
 		'doctype': u'DocField',
-		'fieldname': u'trash_reason',
-		'fieldtype': u'Small Text',
-		'label': u'Trash Reason',
-		'oldfieldname': u'trash_reason',
-		'oldfieldtype': u'Small Text',
-		'permlevel': 1
-	},
-
-	# DocField
-	{
-		'doctype': u'DocField',
 		'fieldname': u'price_list_name',
 		'fieldtype': u'Data',
 		'label': u'Price List Name',
 		'oldfieldname': u'price_list_name',
 		'oldfieldtype': u'Data',
-		'permlevel': 0,
 		'reqd': 1
 	},
 
 	# DocField
 	{
-		'colour': u'White:FFF',
-		'depends_on': u'eval:!doc.__islocal',
-		'doctype': u'DocField',
-		'fieldname': u'price_help',
-		'fieldtype': u'HTML',
-		'label': u'Price Help',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'colour': u'White:FFF',
-		'depends_on': u'eval:!doc.__islocal',
-		'description': u'Click on this button to clear prices for this list in all items',
-		'doctype': u'DocField',
-		'fieldname': u'clear_prices',
-		'fieldtype': u'Button',
-		'label': u'Clear Prices',
-		'permlevel': 0,
-		'trigger': u'Client'
-	},
-
-	# DocField
-	{
 		'doctype': u'DocField',
 		'fieldname': u'file_list',
 		'fieldtype': u'Text',
 		'hidden': 1,
-		'label': u'File List',
-		'permlevel': 0
-	},
-
-	# DocField
-	{
-		'colour': u'White:FFF',
-		'depends_on': u'eval:!doc.__islocal',
-		'description': u'Update prices from the attachment',
-		'doctype': u'DocField',
-		'fieldname': u'update_prices',
-		'fieldtype': u'Button',
-		'label': u'Update Prices',
-		'options': u'update_prices',
-		'permlevel': 0,
-		'trigger': u'Server'
+		'label': u'File List'
 	}
 ]
\ No newline at end of file
diff --git a/public/js/all-app.js b/public/js/all-app.js
index e634cf3..8732fdd 100644
--- a/public/js/all-app.js
+++ b/public/js/all-app.js
@@ -397,8 +397,8 @@
 if(r.server_messages)msgprint(r.server_messages)
 if(r.exc){console.log(r.exc);};if(r['403']){wn.container.change_to('403');}
 if(r.docs){LocalDB.sync(r.docs);}}
-wn.request.call=function(opts){wn.request.prepare(opts);$.ajax({url:opts.url||wn.request.url,data:opts.args,type:opts.type||'POST',dataType:opts.dataType||'json',success:function(r,xhr){wn.request.cleanup(opts,r);opts.success(r,xhr.responseText);},error:function(xhr,textStatus){wn.request.cleanup(opts,{});show_alert('Unable to complete request: '+textStatus)
-if(opts.error)opts.error(xhr)}})}
+wn.request.call=function(opts){wn.request.prepare(opts);$.ajax({url:opts.url||wn.request.url,data:opts.args,type:opts.type||'POST',dataType:opts.dataType||'json',success:function(r,xhr){wn.request.cleanup(opts,r);opts.success&&opts.success(r,xhr.responseText);},error:function(xhr,textStatus){wn.request.cleanup(opts,{});show_alert('Unable to complete request: '+textStatus)
+opts.error&&opts.error(xhr)}})}
 wn.call=function(opts){var args=$.extend({},opts.args)
 if(opts.module&&opts.page){args.cmd=opts.module+'.page.'+opts.page+'.'+opts.page+'.'+opts.method}else if(opts.method){args.cmd=opts.method;}
 for(key in args){if(args[key]&&typeof args[key]!='string'){args[key]=JSON.stringify(args[key]);}}
@@ -1794,7 +1794,7 @@
 this.cleanup_refresh(this);}
 _f.Frm.prototype.cleanup_refresh=function(){var me=this;if(me.fields_dict['amended_from']){if(me.doc.amended_from){unhide_field('amended_from');unhide_field('amendment_date');}else{hide_field('amended_from');hide_field('amendment_date');}}
 if(me.fields_dict['trash_reason']){if(me.doc.trash_reason&&me.doc.docstatus==2){unhide_field('trash_reason');}else{hide_field('trash_reason');}}
-if(me.meta.autoname&&me.meta.autoname.substr(0,6)=='field:'&&!me.doc.__islocal){var fn=me.meta.autoname.substr(6);set_field_permlevel(fn,1);}}
+if(me.meta.autoname&&me.meta.autoname.substr(0,6)=='field:'&&!me.doc.__islocal){var fn=me.meta.autoname.substr(6);cur_frm.toggle_fields(fn,false);}}
 _f.Frm.prototype.refresh_dependency=function(){var me=this;var doc=locals[this.doctype][this.docname];var dep_dict={};var has_dep=false;for(fkey in me.fields){var f=me.fields[fkey];f.dependencies_clear=true;var guardian=f.df.depends_on;if(guardian){if(!dep_dict[guardian])
 dep_dict[guardian]=[];dep_dict[guardian][dep_dict[guardian].length]=f;has_dep=true;}}
 if(!has_dep)return;for(var i=me.fields.length-1;i>=0;i--){var f=me.fields[i];f.guardian_has_value=true;if(f.df.depends_on){var v=doc[f.df.depends_on];if(f.df.depends_on.substr(0,5)=='eval:'){f.guardian_has_value=eval(f.df.depends_on.substr(5));}else if(f.df.depends_on.substr(0,3)=='fn:'){f.guardian_has_value=me.runclientscript(f.df.depends_on.substr(3),me.doctype,me.docname);}else{if(v||(v==0&&!v.substr)){}else{f.guardian_has_value=false;}}
@@ -1858,6 +1858,7 @@
 _f.Frm.prototype.toggle_fields=function(fields,show){if(show){unhide_field(fields)}
 else{hide_field(fields)}}
 _f.Frm.prototype.enable_fields=function(fields,enable){if(typeof fields=='string')fields=[fields];$.each(fields,function(i,f){var field=cur_frm.fields_dict[f];if(field){field.disabled=enable?false:true;field.refresh&&field.refresh();};})}
+_f.Frm.prototype.call_server=function(method,args,callback){$c_obj(cur_frm.get_doclist(),method,args,callback);}
 /*
  *	lib/js/legacy/widgets/form/form_fields.js
  */
diff --git a/public/js/all-web.js b/public/js/all-web.js
index 2e7f1ce..ec171ad 100644
--- a/public/js/all-web.js
+++ b/public/js/all-web.js
@@ -284,8 +284,8 @@
 if(r.server_messages)msgprint(r.server_messages)
 if(r.exc){console.log(r.exc);};if(r['403']){wn.container.change_to('403');}
 if(r.docs){LocalDB.sync(r.docs);}}
-wn.request.call=function(opts){wn.request.prepare(opts);$.ajax({url:opts.url||wn.request.url,data:opts.args,type:opts.type||'POST',dataType:opts.dataType||'json',success:function(r,xhr){wn.request.cleanup(opts,r);opts.success(r,xhr.responseText);},error:function(xhr,textStatus){wn.request.cleanup(opts,{});show_alert('Unable to complete request: '+textStatus)
-if(opts.error)opts.error(xhr)}})}
+wn.request.call=function(opts){wn.request.prepare(opts);$.ajax({url:opts.url||wn.request.url,data:opts.args,type:opts.type||'POST',dataType:opts.dataType||'json',success:function(r,xhr){wn.request.cleanup(opts,r);opts.success&&opts.success(r,xhr.responseText);},error:function(xhr,textStatus){wn.request.cleanup(opts,{});show_alert('Unable to complete request: '+textStatus)
+opts.error&&opts.error(xhr)}})}
 wn.call=function(opts){var args=$.extend({},opts.args)
 if(opts.module&&opts.page){args.cmd=opts.module+'.page.'+opts.page+'.'+opts.page+'.'+opts.method}else if(opts.method){args.cmd=opts.method;}
 for(key in args){if(args[key]&&typeof args[key]!='string'){args[key]=JSON.stringify(args[key]);}}