[selling/buying] [fixes] updated js files of various doctypes related to selling/g/buying
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.js b/accounts/doctype/purchase_invoice/purchase_invoice.js
index 3ddf907..b714a90 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -17,10 +17,28 @@
 cur_frm.cscript.tname = "Purchase Invoice Item";
 cur_frm.cscript.fname = "entries";
 cur_frm.cscript.other_fname = "purchase_tax_details";
+
 wn.require('app/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js');
 wn.require('app/buying/doctype/purchase_common/purchase_common.js');
 
-erpnext.buying.PurchaseInvoiceController = erpnext.buying.BuyingController.extend({
+wn.provide("erpnext.accounts");
+erpnext.accounts.PurchaseInvoiceController = erpnext.buying.BuyingController.extend({
+	setup: function() {
+		this._super();
+		
+	},
+	
+	onload: function() {
+		this._super();
+		
+		if(!this.frm.doc.__islocal) {
+			// show credit_to in print format
+			if(!this.frm.doc.supplier && this.frm.doc.credit_to) {
+				this.frm.set_df_property("credit_to", "print_hide", 0);
+			}
+		}
+	},
+	
 	refresh: function(doc) {
 		this._super();
 		
@@ -34,6 +52,20 @@
 		
 		cur_frm.cscript.is_opening(doc);
 	},
+	
+	credit_to: function() {
+		this.supplier();
+	},
+	
+	write_off_amount: function() {
+		this.calculate_outstanding_amount();
+		this.frm.refresh_fields();
+	},
+	
+	allocated_amount: function() {
+		this.calculate_total_advance();
+		this.frm.refresh_fields();
+	},
 });
 
 // for backward compatibility: combine new and previous states
@@ -55,23 +87,6 @@
 }
 
 
-cur_frm.cscript.credit_to = function(doc,dt,dn) {
-
-	var callback = function(doc, dt, dn) {
-			var doc = locals[doc.doctype][doc.name];
-			if(doc.supplier) {
-				get_server_fields('get_default_supplier_address',
-					JSON.stringify({ supplier: doc.supplier }), '', doc, dt, dn, 1, function() {
-						cur_frm.refresh();
-					});
-				unhide_field(['supplier_address','contact_person']);
-			}
-			cur_frm.refresh();
-	}
-
-	get_server_fields('get_cust', '', '', doc, dt, dn, 1, callback);
-}
-
 cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){
 	
 	cl = getchildren('Purchase Invoice Item', doc.name, cur_frm.cscript.fname, doc.doctype);
@@ -95,17 +110,6 @@
 	if (doc.is_opening == 'Yes') unhide_field('aging_date');
 }
 
-cur_frm.cscript.write_off_amount = function(doc) {
-	doc.total_amount_to_pay = flt(doc.grand_total) - flt(doc.write_off_amount);
-	doc.outstanding_amount = flt(doc.total_amount_to_pay) - flt(doc.total_advance);
-	refresh_many(['outstanding_amount', 'total_amount_to_pay']);
-}
-
-cur_frm.cscript.recalculate = function(doc, cdt, cdn) {
-	cur_frm.cscript.calculate_tax(doc,cdt,cdn);
-	calc_total_advance(doc,cdt,cdn);
-}
-
 cur_frm.cscript.get_items = function(doc, dt, dn) {
 	var callback = function(r,rt) { 
 		unhide_field(['supplier_address', 'contact_person']);				
@@ -114,11 +118,6 @@
 	$c_obj(make_doclist(dt,dn),'pull_details','',callback);
 }
 
-cur_frm.cscript.allocated_amount = function(doc,cdt,cdn) {
-	calc_total_advance(doc, cdt, cdn);
-}
-
-
 cur_frm.cscript.make_bank_voucher = function() {
 	wn.call({
 		method: "accounts.doctype.journal_voucher.journal_voucher.get_default_bank_cash_account",
@@ -204,21 +203,6 @@
 	refresh_field('entries');
 }
 
-calc_total_advance = function(doc,cdt,cdn) {
-	var doc = locals[doc.doctype][doc.name];
-	var el = getchildren('Purchase Invoice Advance',doc.name,'advance_allocation_details')
-	var total_advance = 0;
-	for(var i in el) {
-		if (! el[i].allocated_amount == 0) {
-			total_advance += flt(el[i].allocated_amount);
-		}
-	}
-	doc.total_amount_to_pay = flt(doc.grand_total) - flt(doc.write_off_amount);
-	doc.total_advance = flt(total_advance);
-	doc.outstanding_amount = flt(doc.total_amount_to_pay) - flt(total_advance);
-	refresh_many(['total_advance','outstanding_amount', 'total_amount_to_pay']);
-}
-
 cur_frm.cscript.make_jv = function(doc, dt, dn, bank_account) {
 	var jv = wn.model.make_new_doc_and_get_name('Journal Voucher');
 	jv = locals['Journal Voucher'][jv];
diff --git a/accounts/doctype/sales_invoice/sales_invoice.js b/accounts/doctype/sales_invoice/sales_invoice.js
index 800cd2b..10853ea 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/accounts/doctype/sales_invoice/sales_invoice.js
@@ -22,17 +22,20 @@
 // print heading
 cur_frm.pformat.print_heading = 'Invoice';
 
-wn.require('app/selling/doctype/sales_common/sales_common.js');
 wn.require('app/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js');
 wn.require('app/utilities/doctype/sms_control/sms_control.js');
+wn.require('app/selling/doctype/sales_common/sales_common.js');
 
-erpnext.selling.SalesInvoiceController = erpnext.selling.SellingController.extend({
+wn.provide("erpnext.accounts");
+erpnext.accounts.SalesInvoiceController = erpnext.selling.SellingController.extend({
 	onload: function() {
 		this._super();
 		
-		// show debit_to in print format
-		if(!this.frm.doc.customer && this.frm.doc.debit_to) {
-			this.frm.set_df_property("debit_to", "print_hide", 0);
+		if(!this.frm.doc.__islocal) {
+			// show debit_to in print format
+			if(!this.frm.doc.customer && this.frm.doc.debit_to) {
+				this.frm.set_df_property("debit_to", "print_hide", 0);
+			}
 		}
 	},
 	
@@ -41,10 +44,6 @@
 		
 		cur_frm.cscript.is_opening(doc, dt, dn);
 
-		// Show / Hide button
-		cur_frm.clear_custom_buttons();
-		// if (!cur_frm.cscript.is_onload)	cur_frm.cscript.hide_price_list_currency(doc, dt, dn); 
-
 		if(doc.docstatus==1) {
 			cur_frm.add_custom_button('View Ledger', cur_frm.cscript.view_ledger_entry);
 			cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
@@ -78,10 +77,39 @@
 	debit_to: function() {
 		this.customer();
 	},
+	
+	allocated_amount: function() {
+		this.calculate_total_advance();
+		this.frm.refresh_fields();
+	},
+	
+	write_off_outstanding_amount_automatically: function() {
+		if(cint(this.frm.doc.write_off_outstanding_amount_automatically)) {
+			wn.model.round_floats_in(this.frm.doc, ["grand_total", "paid_amount"]);
+			this.frm.set_value("write_off_amount", 
+				flt(this.frm.doc.grand_total - this.frm.doc.paid_amount), precision("write_off_amount"));
+		}
+		
+		this.frm.runclientscript("write_off_amount");
+		
+		// TODO doubt?
+		// if write off amount = grand total - paid amount
+		// then why is outstanding amount = grand total - write off amount - paid amount - advance
+		// when write off amount already is grand total - paid amount!
+	},
+	
+	write_off_amount: function() {
+		this.calculate_outstanding_amount();
+		this.frm.refresh_fields();
+	},
+	
+	paid_amount: function() {
+		this.write_off_outstanding_amount_automatically();
+	},
 });
 
 // for backward compatibility: combine new and previous states
-$.extend(cur_frm.cscript, new erpnext.selling.SalesInvoiceController({frm: cur_frm}));
+$.extend(cur_frm.cscript, new erpnext.accounts.SalesInvoiceController({frm: cur_frm}));
 
 // Hide Fields
 // ------------
@@ -129,35 +157,10 @@
 	cur_frm.cscript.hide_fields(doc, dt, dn);
 }
 
-cur_frm.cscript.warehouse = function(doc, cdt , cdn) {
-	var d = locals[cdt][cdn];
-	if (!d.item_code) { msgprint("please enter item code first"); return };
-	if (d.warehouse) {
-		arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.warehouse +"'}";
-		get_server_fields('get_actual_qty',arg,'entries',doc,cdt,cdn,1);
-	}
-}
-
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
 }
 
-cur_frm.cscript.write_off_outstanding_amount_automatically = function(doc) {
-	if (doc.write_off_outstanding_amount_automatically == 1) 
-		doc.write_off_amount = flt(doc.grand_total) - flt(doc.paid_amount);
-	
-	doc.outstanding_amount = flt(doc.grand_total) - flt(doc.paid_amount) - flt(doc.write_off_amount);
-	refresh_field(['write_off_amount', 'outstanding_amount']);
-}
-
-cur_frm.cscript.paid_amount = function(doc) {
-	cur_frm.cscript.write_off_outstanding_amount_automatically(doc);
-}
-
-cur_frm.cscript.write_off_amount = function(doc) {
-	cur_frm.cscript.write_off_outstanding_amount_automatically(doc);
-}
-
 cur_frm.fields_dict['entries'].grid.onrowadd = function(doc, cdt, cdn){
 
 	cl = getchildren('Sales Invoice Item', doc.name, cur_frm.cscript.fname, doc.doctype);
@@ -193,12 +196,6 @@
 
 
 
-// Allocated Amount in advances table
-// -----------------------------------
-cur_frm.cscript.allocated_amount = function(doc,cdt,cdn){
-	cur_frm.cscript.calc_adjustment_amount(doc,cdt,cdn);
-}
-
 //Make Delivery Note Button
 //-----------------------------
 
@@ -363,19 +360,6 @@
 	refresh_field(cur_frm.cscript.fname);
 }
 
-cur_frm.cscript.calc_adjustment_amount = function(doc,cdt,cdn) {
-	var doc = locals[doc.doctype][doc.name];
-	var el = getchildren('Sales Invoice Advance',doc.name,'advance_adjustment_details');
-	var total_adjustment_amt = 0
-	for(var i in el) {
-			total_adjustment_amt += flt(el[i].allocated_amount)
-	}
-	doc.total_advance = flt(total_adjustment_amt);
-	doc.outstanding_amount = flt(doc.grand_total) - flt(total_adjustment_amt) - flt(doc.paid_amount) - flt(doc.write_off_amount);
-	refresh_many(['total_advance','outstanding_amount']);
-}
-
-
 // Make Journal Voucher
 // --------------------
 cur_frm.cscript.make_jv = function(doc, dt, dn, bank_account) {
diff --git a/accounts/doctype/sales_invoice/sales_invoice.py b/accounts/doctype/sales_invoice/sales_invoice.py
index d313a32..55b2336 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/accounts/doctype/sales_invoice/sales_invoice.py
@@ -599,15 +599,6 @@
 		
 		get_obj('Stock Ledger', 'Stock Ledger').update_stock(self.values)
 		
-	def get_actual_qty(self,args):
-		args = eval(args)
-		actual_qty = webnotes.conn.sql("select actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (args['item_code'], args['warehouse']), as_dict=1)
-		ret = {
-			 'actual_qty' : actual_qty and flt(actual_qty[0]['actual_qty']) or 0
-		}
-		return ret
-
-
 	def make_gl_entries(self):
 		from accounts.general_ledger import make_gl_entries, merge_similar_entries
 		
diff --git a/buying/doctype/purchase_common/purchase_common.js b/buying/doctype/purchase_common/purchase_common.js
index 3202122..65b44c3 100644
--- a/buying/doctype/purchase_common/purchase_common.js
+++ b/buying/doctype/purchase_common/purchase_common.js
@@ -27,24 +27,34 @@
 		var me = this;
 		
 		if(this.frm.fields_dict.price_list_name) {
-			this.frm.fields_dict.price_list_name.get_query = function() {
+			this.frm.set_query("price_list_name", function() {
 				return repl("select distinct price_list_name from `tabItem Price` \
 					where buying = 1 and price_list_name like \"%s%%\"");
-			};
-		}
-		
-		if(this.frm.fields_dict.price_list_currency) {
-			this.frm.fields_dict.price_list_currency.get_query = function() {
+			});
+			
+			this.frm.set_query("price_list_currency", function() {
 				return repl("select distinct ref_currency from `tabItem Price` \
 					where price_list_name=\"%(price_list_name)s\" and buying = 1 \
 					and ref_currency like \"%s%%\"", 
 					{price_list_name: me.frm.doc.price_list_name});
-			};
+			});
 		}
+		
+		if(this.frm.fields_dict.supplier) {
+			this.frm.set_query("supplier", erpnext.utils.supplier_query);
+		}
+		
+		this.frm.set_query("item_code", this.frm.cscript.fname, function() {
+			if(me.frm.doc.is_subcontracted == "Yes") {
+				return erpnext.queries.item({'ifnull(tabItem.is_sub_contracted_item, "No")': "Yes"});
+			} else {
+				return erpnext.queries.item({'ifnull(tabItem.is_purchase_item, "No")': "Yes"});
+			}
+		});
 	},
 	
 	validate: function() {
-		
+		this.calculate_taxes_and_totals();
 	},
 	
 	supplier: function() {
@@ -100,7 +110,7 @@
 					},
 					callback: function(r) {
 						if(!r.exc) {
-							me.ref_rate(me.frm.doc, cdt, cdn);
+							me.import_ref_rate(me.frm.doc, cdt, cdn);
 						}
 					}
 				});
@@ -108,13 +118,102 @@
 		}
 	},
 	
-	price_list_name: function(callback_fn) {
+	price_list_name: function() {
 		this._super("buying");
 	},
 	
+	import_ref_rate: function(doc, cdt, cdn) {
+		var item = wn.model.get_doc(cdt, cdn);
+		wn.model.round_floats_in(item, ["import_ref_rate", "discount_rate"]);
+		
+		item.import_rate = flt(item.import_ref_rate * (1 - item.discount_rate / 100.0),
+			precision("import_rate", item));
+		
+		this.calculate_taxes_and_totals();
+	},
+	
+	discount_rate: function(doc, cdt, cdn) {
+		this.import_rate(doc, cdt, cdn);
+	},
+	
+	import_rate: function(doc, cdt, cdn) {
+		var item = wn.model.get_doc(cdt, cdn);
+		wn.model.round_floats_in(item, ["import_rate", "discount_rate"]);
+		
+		if(item.import_ref_rate) {
+			item.discount_rate = flt((1 - item.import_rate / item.import_ref_rate) * 100.0,
+				precision("discount_rate", item));
+		} else {
+			item.discount_rate = 0.0;
+		}
+		
+		this.calculate_taxes_and_totals();
+	},
+	
+	uom: function(doc, cdt, cdn) {
+		var me = this;
+		var item = wn.model.get_doc(cdt, cdn);
+		if(item.item_code && item.uom) {
+			this.frm.call({
+				method: "buying.utils.get_conversion_factor",
+				child: item,
+				args: {
+					item_code: item.item_code,
+					uom: item.uom,
+				},
+				callback: function(r) {
+					if(!r.exc) {
+						me.conversion_factor(me.frm.doc, cdt, cdn);
+					}
+				}
+			});
+		}
+	},
+	
+	qty: function(doc, cdt, cdn) {
+		this._super(doc, cdt, cdn);
+		this.conversion_factor(doc, cdt, cdn);
+	},
+	
+	conversion_factor: function(doc, cdt, cdn) {
+		if(wn.meta.get_docfield(cdt, "stock_qty", cdn)) {
+			var item = wn.model.get_doc(cdt, cdn);
+			wn.model.round_floats_in(item, ["qty", "conversion_factor"])
+			item.stock_qty = flt(item.qty * item.conversion_factor, precision("stock_qty", item));
+			refresh_field("stock_qty", item.name, item.parentfield);
+		}
+	},
+	
+	warehouse: function(doc, cdt, cdn) {
+		var item = wn.model.get_doc(cdt, cdn);
+		if(item.item_code && item.warehouse) {
+			this.frm.call({
+				method: "buying.utils.get_conversion_factor",
+				child: item,
+				args: {
+					item_code: item.item_code,
+					warehouse: item.warehouse,
+				}
+			});
+		}
+	},
+	
+	project_name: function(doc, cdt, cdn) {
+		var item = wn.model.get_doc(cdt, cdn);
+		if(item.project_name) {
+			$.each(wn.model.get_doclist(this.frm.doc.doctype, this.frm.doc.name, {parentfield: this.fname}),
+				function(i, other_item) { 
+					if(!other_item.project_name) {
+						other_item.project_name = item.project_name;
+						refresh_field("project_name", other_item.name, other_item.parentfield);
+					}
+				});
+		}
+	},
+	
 	calculate_taxes_and_totals: function() {
 		this._super();
-		this.calculate_outstanding_amount();
+		this.calculate_total_advance();
 		this.frm.refresh_fields();
 	},
 	
@@ -164,6 +263,7 @@
 		this.frm.doc.total_tax = flt(this.frm.doc.grand_total - this.frm.doc.net_total,
 			precision("total_tax"));
 		
+		// rounded totals
 		if(wn.meta.get_docfield(this.frm.doc.doctype, "rounded_total", this.frm.doc.name)) {
 			this.frm.doc.rounded_total = Math.round(this.frm.doc.grand_total);
 		}
@@ -171,6 +271,22 @@
 		if(wn.meta.get_docfield(this.frm.doc.doctype, "rounded_total_import", this.frm.doc.name)) {
 			this.frm.doc.rounded_total_import = Math.round(this.frm.doc.grand_total_import);
 		}
+		
+		// other charges added/deducted
+		if(tax_count) {
+			this.frm.doc.other_charges_added = wn.utils.sum($.map(this.frm.tax_doclist, 
+				function(tax) { return tax.add_deduct_tax == "Add" ? tax.tax_amount : 0.0; }));
+		
+			this.frm.doc.other_charges_deducted = wn.utils.sum($.map(this.frm.tax_doclist, 
+				function(tax) { return tax.add_deduct_tax == "Deduct" ? tax.tax_amount : 0.0; }));
+			
+			wn.model.round_floats_in(this.frm.doc, ["other_charges_added", "other_charges_deducted"]);
+			
+			this.frm.doc.other_charges_added_import = flt(this.frm.doc.other_charges_added / this.frm.doc.conversion_rate,
+				precision("other_charges_added_import"));
+			this.frm.doc.other_charges_deducted_import = flt(this.frm.doc.other_charges_deducted / this.frm.doc.conversion_rate,
+				precision("other_charges_deducted_import"));
+		}
 	},
 	
 	_cleanup: function() {
@@ -189,9 +305,13 @@
 		}
 	},
 	
+	calculate_total_advance: function() {
+		this._super("Purchase Invoice", "advance_allocation_details");
+	},
+	
 	calculate_outstanding_amount: function() {
 		if(this.frm.doc.doctype == "Purchase Invoice" && this.frm.doc.docstatus < 2) {
-			wn.model.round_floats_in(this.frm.doc, ["total_advance", "write_off_amount"]);
+			wn.model.round_floats_in(this.frm.doc, ["grand_total", "total_advance", "write_off_amount"]);
 			this.frm.doc.total_amount_to_pay = flt(this.frm.doc.grand_total - this.frm.doc.write_off_amount,
 				precision("total_amount_to_pay"));
 			this.frm.doc.outstanding_amount = flt(this.frm.doc.total_amount_to_pay - this.frm.doc.total_advance,
@@ -210,6 +330,15 @@
 		}
 	},
 	
+	show_item_wise_taxes: function() {
+		$(this.get_item_wise_taxes_html())
+			.appendTo($(this.frm.fields_dict.tax_calculation.wrapper).empty());
+	},
+	
+	recalculate: function() {
+		this.calculate_taxes_and_totals();
+	},
+	
 	set_dynamic_labels: function(doc, dt, dn) {
 		var company_currency = this.get_company_currency();
 		
@@ -305,6 +434,8 @@
 			$wrapper.find('[data-grid-fieldname="'+fname+'"]').text(label);
 		});
 	},
+	
+	
 });
 
 // to save previous state of cur_frm.cscript
@@ -319,498 +450,3 @@
 
 var tname = cur_frm.cscript.tname;
 var fname = cur_frm.cscript.fname;
-
-//==================== Item Code Get Query =======================================================
-// Only Is Purchase Item = 'Yes' and Items not moved to trash are allowed.
-cur_frm.fields_dict[fname].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
-	if (doc.is_subcontracted =="Yes") {
-		return erpnext.queries.item({
-			'ifnull(tabItem.is_sub_contracted_item, "No")': 'Yes'
-		})
-	} else {
-		return erpnext.queries.item({
-			'ifnull(tabItem.is_purchase_item, "No")': 'Yes'
-		})
-	}
-}
-
-//==================== Update Stock Qty ==========================================================
-cur_frm.cscript.update_stock_qty = function(doc,cdt,cdn){
-	d = locals[cdt][cdn]
-	// Step 1:=> Check if qty , uom, conversion_factor
-	if (d.qty && d.uom && d.conversion_factor){
-		// Step 2:=> Set stock_qty = qty * conversion_factor
-		d.stock_qty = flt(flt(d.qty) * flt(d.conversion_factor));
-		// Step 3:=> Refer stock_qty field a that particular row.
-		refresh_field('stock_qty' , d.name,fname);
-	}
-}
-
-//==================== UOM ======================================================================
-cur_frm.cscript.uom = function(doc, cdt, cdn, args) {
-	if(!args) args = {};
-	
-	// args passed can contain conversion_factor
-	var d = locals[cdt][cdn];
-	$.extend(args, {
-		item_code: d.item_code,
-		uom: d.uom,
-		stock_qty: flt(d.stock_qty),
-	});
-	
-	if(d.item_code && d.uom) {
-		cur_frm.call({
-			method: "buying.doctype.purchase_common.purchase_common.get_uom_details",
-			args: { args: args },
-			child: d,
-			callback: function(r) {
-				cur_frm.cscript.calc_amount(doc, 2);
-			}
-		});
-	}
-}
-
-
-//==================== Conversion factor =========================================================
-cur_frm.cscript.conversion_factor = function(doc, cdt, cdn) {
-	var item = locals[cdt][cdn];
-	
-	cur_frm.cscript.uom(doc, cdt, cdn, { conversion_factor: item.conversion_factor });
-}
-
-//==================== stock qty ======================================================================
-cur_frm.cscript.stock_qty = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	if(d.uom && d.qty){
-		d.conversion_factor = flt(d.stock_qty)/flt(d.qty);
-		refresh_field('conversion_factor', d.name, fname);
-	}
-}
-
-//==================== Warehouse ================================================================
-cur_frm.cscript.warehouse = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	if (d.item_code && d.warehouse) {
-		str_arg = "{'item_code':'" +	(d.item_code?d.item_code:'') + "', 'warehouse':'" + (d.warehouse?d.warehouse:'') + "'}"
-		get_server_fields('get_bin_details', str_arg, fname, doc, cdt, cdn, 1);
-	}	
-}
-
-//=================== Quantity ===================================================================
-cur_frm.cscript.qty = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	// Step 1: => Update Stock Qty 
-	cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
-	// Step 2: => Calculate Amount
-	cur_frm.cscript.calc_amount(doc, 2);
-}
-
-
-//=================== Purchase Rate ==============================================================
-cur_frm.cscript.purchase_rate = function(doc, cdt, cdn) {
-	cur_frm.cscript.calc_amount(doc, 2);
-}
-
-//==================== Import Rate ================================================================
-cur_frm.cscript.import_rate = function(doc, cdt, cdn) {
-	cur_frm.cscript.calc_amount(doc, 1);
-}
-
-//==================== Discount Rate ================================================================
-cur_frm.cscript.discount_rate = function(doc, cdt, cdn) {
-	cur_frm.cscript.calc_amount(doc, 4);
-}
-//==================== Purchase Ref Rate ================================================================
-cur_frm.cscript.purchase_ref_rate = function(doc, cdt, cdn) {
-	cur_frm.cscript.calc_amount(doc, 4);
-}
-//==================== Import Ref Rate ================================================================
-cur_frm.cscript.import_ref_rate = function(doc, cdt, cdn) {
-	cur_frm.cscript.calc_amount(doc, 5);
-}
-
-//==================== Validate ====================================================================
-cur_frm.cscript.validate = function(doc, cdt, cdn) {
-	cur_frm.cscript.calc_amount(doc, 1);
-
-	// calculate advances if pv
-	if(doc.docstatus == 0 && doc.doctype == 'Purchase Invoice') calc_total_advance(doc, cdt, cdn);
-}
-
-// **************** RE-CALCULATE VALUES ***************************
-
-cur_frm.cscript.recalculate_values = function(doc, cdt, cdn) {
-	cur_frm.cscript.calculate_tax(doc,cdt,cdn);
-}
-
-cur_frm.cscript.calculate_tax = function(doc, cdt, cdn) {
-	var other_fname	= cur_frm.cscript.other_fname;
-
-	var cl = getchildren('Purchase Taxes and Charges', doc.name, other_fname, doc.doctype);
-	for(var i = 0; i<cl.length; i++){
-		cl[i].total_tax_amount = 0;
-		cl[i].total_amount = 0;
-		cl[i].tax_amount = 0;										// this is done to calculate other charges
-		cl[i].total = 0;
-		if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
-			alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
-			validated = false;
-		}
-	}
-	cur_frm.cscript.calc_amount(doc, 1);
-}
-
-
-
-cur_frm.cscript.get_item_wise_tax_detail = function( doc, rate, cl, i, tax, t) {
-	doc = locals[doc.doctype][doc.name];
-	var detail = '';
-	detail = cl[i].item_code + " : " + cstr(rate) + NEWLINE;
-	return detail;
-}
-
-cur_frm.cscript.amount = function(doc, cdt, cdn) {
-	cur_frm.cscript.calc_amount(doc, 3);
-}
-
-
-//====================== Calculate Amount for PO and PR not for PV	============================================================
-cur_frm.cscript.calc_amount = function(doc, n) {
-	// Set defaults
-	doc = locals[doc.doctype][doc.name]
-	var other_fname	= cur_frm.cscript.other_fname;
-	if(!flt(doc.conversion_rate)) { doc.conversion_rate = 1; refresh_field('conversion_rate'); }
-	if(!n) n=0;
-	var net_total = 0;
-	var net_total_import = 0;
-	
-	var cl = getchildren(tname, doc.name, fname);
-	
-	for(var i=0;i<cl.length;i++) 
-	{
-	var rate_fld = (doc.doctype != 'Purchase Invoice') ? 'purchase_rate': 'rate';
-		var tmp = {};
-	if(!cl[i].discount_rate) cl[i].discount_rate = 0;
-
-		if(n == 1){ 
-			set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
-		set_multiple(tname, cl[i].name, {
-			'discount_rate': flt(cl[i].import_ref_rate) ? 
-				flt(flt( flt( flt(cl[i].import_ref_rate) - flt(cl[i].import_rate) ) * 100 )/ 
-					flt(cl[i].import_ref_rate))	: 0 }, fname);
-		tmp[rate_fld] = flt(doc.conversion_rate) * flt(cl[i].import_rate);
-			set_multiple(tname, cl[i].name, tmp, fname);
-
-			set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(doc.conversion_rate) * flt(cl[i].import_rate))}, fname);
-			set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) * flt(cl[i].import_rate))}, fname);
-
-		}else if(n == 2){
-		set_multiple(tname, cl[i].name, {'purchase_ref_rate':flt(cl[i].import_ref_rate)*flt(doc.conversion_rate)}, fname);
-		set_multiple(tname, cl[i].name, {
-			'discount_rate': flt(cl[i].purchase_ref_rate) ? 
-				flt(flt( flt( flt(cl[i].purchase_ref_rate) - flt(cl[i][rate_fld]) ) * 100 )/
-				flt(cl[i].purchase_ref_rate)) : 0 }, fname);
-			set_multiple(tname, cl[i].name, {'amount': flt(flt(cl[i].qty) * flt(cl[i][rate_fld])),}, fname);
-		set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate)) }, fname);
-			set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
-
-	}else if(n == 3){
-		tmp[rate_fld] = flt(flt(cl[i].amount) / flt(cl[i].qty));
-			set_multiple(tname, cl[i].name, tmp, fname);
-			set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-			set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname);
-
-		}else if( n==4){
-
-		set_multiple(tname, cl[i].name, {'import_ref_rate': flt(flt(cl[i].purchase_ref_rate) / flt(doc.conversion_rate))}, fname);
-
-			tmp[rate_fld] = flt( flt(cl[i].purchase_ref_rate) - flt(flt(cl[i].purchase_ref_rate)*flt(cl[i].discount_rate)/100) )
-		set_multiple(tname, cl[i].name, tmp, fname);
-		set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-		set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
-		set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-	}else if( n==5){	
-		tmp[rate_fld] = flt( flt(cl[i].import_ref_rate) - flt(flt(cl[i].import_ref_rate)*flt(cl[i].discount_rate)/100) ) * flt(doc.conversion_rate);
-		set_multiple(tname, cl[i].name, {'purchase_ref_rate': flt(flt(cl[i].import_ref_rate) * flt(doc.conversion_rate))}, fname);
-		set_multiple(tname, cl[i].name, tmp, fname);
-		set_multiple(tname, cl[i].name, {'import_rate': flt(flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-		set_multiple(tname, cl[i].name, {'amount':flt(flt(cl[i].qty) * flt(cl[i][rate_fld]))}, fname);
-		set_multiple(tname, cl[i].name, {'import_amount': flt(flt(cl[i].qty) *	flt(cl[i][rate_fld]) / flt(doc.conversion_rate))}, fname); 
-	}
-	
-		if (n != 3){
-			net_total += flt(flt(cl[i].qty) * flt(cl[i][rate_fld]));
-			net_total_import += flt(flt(cl[i].qty) * flt(cl[i].import_rate));
-		} else if(n == 3){
-			net_total += flt(cl[i].amount);
-			net_total_import += flt(cl[i].amount) / flt(doc.conversion_rate);
-		}
-		//update stock uom
-		cur_frm.cscript.update_stock_qty(doc, tname, cl[i].name);
-	}
-	doc.net_total = flt(net_total) ;
-	doc.net_total_import = flt(net_total_import) ;
-	refresh_field('net_total');
-	refresh_field('net_total_import');
-	
-	cur_frm.cscript.val_cal_charges(doc, tname, fname, other_fname);
-}
-
-
-//======== Function was broken away from cur_frm.cscript.calc_amount as PV has fieldname 'rate' instead of 'purchase_rate'===========
-cur_frm.cscript.val_cal_charges = function(doc, tname, fname, other_fname){
-
-	doc = locals[doc.doctype][doc.name]
-	if(flt(doc.net_total) > 0) {
-		var cl = getchildren('Purchase Taxes and Charges', doc.name, other_fname,doc.doctype);
-		for(var i = 0; i<cl.length; i++){
-			cl[i].total_tax_amount = 0;
-			cl[i].total_amount = 0;
-			cl[i].tax_amount = 0;										// this is done to calculate other charges
-			cl[i].total = 0;
-			cl[i].item_wise_tax_detail = "";
-			if(in_list(['On Previous Row Amount','On Previous Row Total'],cl[i].charge_type) && !cl[i].row_id){
-				alert("Please Enter Row on which amount needs to be calculated for row : "+cl[i].idx);
-				validated = false;
-			}
-		}
-		cur_frm.cscript.calc_other_charges(doc , tname , fname , other_fname); // calculate other charges
-	}
-	cur_frm.cscript.calc_doc_values(doc, tname, fname, other_fname); // calculates total amounts
-
-	refresh_many(['net_total', 'grand_total', 'rounded_total', 'grand_total_import', 'rounded_total_import', 'in_words', 'in_words_import', 'purchase_tax_details', 'total_tax', 'other_charges_added', 'other_charges_deducted', 'net_total_import', 'other_charges_added_import', 'other_charges_deducted_import']);
-
-}
-
-
-// ******************************* OTHER CHARGES *************************************
-cur_frm.cscript.calc_other_charges = function(doc , tname , fname , other_fname) {
-	doc = locals[doc.doctype][doc.name];
-	// make display area
-	// ------------------
-
-	
-	cur_frm.fields_dict['tax_calculation'].disp_area.innerHTML = '<b style="padding: 8px 0px;">Calculation Details for Taxes, Charges and Landed Cost:</b>';
-	var cl = getchildren(tname, doc.name, fname);
-	var tax = getchildren('Purchase Taxes and Charges', doc.name, other_fname,doc.doctype);
-	// make display table
-	// ------------------
-	var otc = make_table(cur_frm.fields_dict['tax_calculation'].disp_area, cl.length + 1, tax.length + 1, '90%',[],{border:'1px solid #AAA',padding:'2px'});
-	$y(otc,{marginTop:'8px'});
-	
-	var tax_desc = {}; var tax_desc_rates = []; var net_total = 0;
-	
-	
-	for(var i=0;i<cl.length;i++) {
-		var item_tax = 0;
-		if(doc.doctype != 'Purchase Invoice') net_total += flt(flt(cl[i].qty) * flt(cl[i].purchase_rate));
-		else if(doc.doctype == 'Purchase Invoice') net_total += flt(flt(cl[i].qty) * flt(cl[i].rate));
-
-		var prev_total = flt(cl[i].amount);
-		if(cl[i].item_tax_rate) {
-			try {
-				var check_tax = JSON.parse(cl[i].item_tax_rate);				//to get in dictionary
-			} catch(exception) {
-				var check_tax = eval('var a='+cl[i].item_tax_rate+';a');        //to get in dictionary				 
-			}
-		}
-		
-		// Add Item Code in new Row 
-		//--------------------------
-		$td(otc,i+1,0).innerHTML = cl[i].item_code;
-		
-		var total = net_total;
-		for(var t=0;t<tax.length;t++){
- 
-			var account = tax[t].account_head;
-			$td(otc,0,t+1).innerHTML = account?account:'';
-			//Check For Rate
-			if(cl[i].item_tax_rate && check_tax[account]!=null)	{
-				rate = flt(check_tax[account]);
-			} else {
-				// if particular item doesn't have particular rate it will take other charges rate
-				rate = flt(tax[t].rate);
-			}
-
-			//Check For Rate and get tax amount
-			var tax_amount = cur_frm.cscript.check_charge_type_and_get_tax_amount(doc,tax,t, cl[i], rate);
-			
-			//enter item_wise_tax_detail i.e. tax rate on each item
-			
-			item_wise_tax_detail = cur_frm.cscript.get_item_wise_tax_detail( doc, rate, cl, i, tax, t);
-			
-			
-			if(tax[t].add_deduct_tax == 'Add'){
-				// this is calculation part for all types
-				if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
-				tax[t].total_amount = flt(tax_amount);		 //stores actual tax amount in virtual field
-				tax[t].total_tax_amount = flt(prev_total);			//stores total amount in virtual field
-				tax[t].tax_amount += flt(tax_amount);			 
-				var total_amount = flt(tax[t].tax_amount);
-				total_tax_amount = flt(tax[t].total_tax_amount) + flt(total_amount);
-				if(tax[t].category != "Valuation"){
-					set_multiple('Purchase Taxes and Charges', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':roundNumber(total_amount, 2), 'total':roundNumber(flt(total)+flt(tax[t].tax_amount), 2)}, other_fname);
-					prev_total += flt(tax[t].total_amount);
-					total += flt(tax[t].tax_amount);	// for adding total to previous amount			 
-				}
-				else{
-					set_multiple('Purchase Taxes and Charges', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'amount':roundNumber(total_amount, 2), 'total':roundNumber(flt(total), 2)}, other_fname);
-					prev_total = prev_total;
-				}
-				//prev_total += flt(tax[t].total_amount);	 // for previous row total
-
-				if(tax[t].charge_type == 'Actual')
-					$td(otc,i+1,t+1).innerHTML = format_currency(tax[t].total_amount, erpnext.get_currency(doc.company));
-				else
-					$td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +format_currency(tax[t].total_amount, erpnext.get_currency(doc.company));
-
-				if (tax[t].category != "Total"){
-					item_tax += tax[t].total_amount;
-				}
-			}
-			else if(tax[t].add_deduct_tax == 'Deduct'){
-				// this is calculation part for all types
-				if(tax[t].charge_type != "Actual") tax[t].item_wise_tax_detail += item_wise_tax_detail;
-				tax[t].total_amount = flt(tax_amount);		 //stores actual tax amount in virtual field
-				tax[t].total_tax_amount = flt(prev_total);			//stores total amount in virtual field
-				tax[t].tax_amount += flt(tax_amount);
-				var total_amount = flt(tax[t].tax_amount);
-				total_tax_amount = flt(tax[t].total_tax_amount) - flt(total_amount);
-				if(tax[t].category != "Valuation"){
-					set_multiple('Purchase Taxes and Charges', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':roundNumber(total_amount, 2), 'total':roundNumber(flt(total)-flt(tax[t].tax_amount), 2)}, other_fname);
-					prev_total -= flt(tax[t].total_amount); 
-					total -= flt(tax[t].tax_amount);	// for adding total to previous amount			 
-				}
-				else{
-					set_multiple('Purchase Taxes and Charges', tax[t].name, { 'item_wise_tax_detail':tax[t].item_wise_tax_detail, 'tax_amount':roundNumber(total_amount, 2), 'total':roundNumber(flt(total), 2)}, other_fname);
-					prev_total = prev_total;
-				}
-				//prev_total += flt(tax[t].total_amount);	 // for previous row total
-
-				if(tax[t].charge_type == 'Actual')
-					$td(otc,i+1,t+1).innerHTML = format_currency(tax[t].total_amount, erpnext.get_currency(doc.company));
-				else
-					$td(otc,i+1,t+1).innerHTML = '('+fmt_money(rate) + '%) ' +format_currency(tax[t].total_amount, erpnext.get_currency(doc.company));
-
-				if (tax[t].category != "Total"){
-					item_tax -= tax[t].total_amount;
-				}
-			}			
-			
-			
-		}
-		set_multiple(tname, cl[i].name, {'item_tax_amount': item_tax }, fname);
-	}
-	for(var t=0;t<tax.length;t++){
-		tax[t].tax_amount = roundNumber(tax[t].tax_amount, 2);
-	}
-}
-
-
-cur_frm.cscript.check_charge_type_and_get_tax_amount = function(doc, tax, t, cl, rate, print_amt) {
-	doc = locals[doc.doctype][doc.name];
-
-	var tax_amount = 0;
-	if(tax[t].charge_type == 'Actual') {
-		var value = flt(tax[t].rate) / flt(doc.net_total);	 // this give the ratio in which all items are divided					 
-		return tax_amount = flt(value) * flt(cl.amount);
-	 }	 
-	else if(tax[t].charge_type == 'On Net Total') {
-		return tax_amount = (flt(rate) * flt(cl.amount) / 100);
-	}
-	else if(tax[t].charge_type == 'On Previous Row Amount'){
-		var row_no = (tax[t].row_id).toString();
-		var row = (row_no).split("+");			// splits the values and stores in an array
-		for(var r = 0;r<row.length;r++){
-			var id = cint(row[r].replace(/^\s+|\s+$/g,""));
-			tax_amount += (flt(rate) * flt(tax[id-1].total_amount) / 100);
-		}
-		var row_id = row_no.indexOf("/");
-		if(row_id != -1) {
-			rate = '';
-			var row = (row_no).split("/");			// splits the values and stores in an array
-			if(row.length>2) alert("You cannot enter more than 2 nos. for division");
-			var id1 = cint(row[0].replace(/^\s+|\s+$/g,""));
-			var id2 = cint(row[1].replace(/^\s+|\s+$/g,""));
-			tax_amount = flt(tax[id1-1].total_amount) / flt(tax[id2-1].total_amount);
-		}
-		return tax_amount
-	}
-	else if(tax[t].charge_type == 'On Previous Row Total') {
-		var row = cint(tax[t].row_id);
-		if(tax[row-1].add_deduct_tax == 'Add'){
-			return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)+flt(tax[row-1].total_amount)) / 100;
-		 }
-		else if(tax[row-1].add_deduct_tax == 'Deduct'){
-			return tax_amount = flt(rate) * (flt(tax[row-1].total_tax_amount)-flt(tax[row-1].total_amount)) / 100;
-		 }
-	}
-}
-
-// ******* Calculation of total amounts of document (item amount + other charges)****************
-cur_frm.cscript.calc_doc_values = function(doc, tname, fname, other_fname) {
-	doc = locals[doc.doctype][doc.name];
-	var net_total = 0; var total_tax = 0; var other_charges_added = 0; 
-	var other_charges_deducted = 0;
-	var cl = getchildren(tname, doc.name, fname);
-	for(var i = 0; i<cl.length; i++){
-		net_total += flt(cl[i].amount);
-	}
-	var d = getchildren('Purchase Taxes and Charges', doc.name, other_fname,doc.doctype);
-	for(var j = 0; j<d.length; j++){
-		if(d[j].category != 'Valuation'){
-			
-			if(d[j].add_deduct_tax == 'Add'){
-				other_charges_added += flt(d[j].tax_amount);
-				total_tax += flt(d[j].tax_amount);
-			}
-			if(d[j].add_deduct_tax == 'Deduct'){
-				other_charges_deducted += flt(d[j].tax_amount);
-				total_tax -= flt(d[j].tax_amount);
-			}
-		}
-	}
-	doc.net_total = flt(net_total);
-	doc.total_tax = flt(total_tax);
-
-	doc.other_charges_added = roundNumber(flt(other_charges_added), 2);
-	doc.other_charges_deducted = roundNumber(flt(other_charges_deducted), 2);
-	doc.grand_total = roundNumber(flt(flt(net_total) + flt(other_charges_added) - flt(other_charges_deducted)), 2);
-	doc.rounded_total = Math.round(doc.grand_total);
-	doc.net_total_import = roundNumber(flt(flt(net_total) / flt(doc.conversion_rate)), 2);
-	doc.other_charges_added_import = roundNumber(flt(flt(other_charges_added) / flt(doc.conversion_rate)), 2);
-	doc.other_charges_deducted_import = roundNumber(flt(flt(other_charges_deducted) / flt(doc.conversion_rate)), 2);
-	doc.grand_total_import = roundNumber(flt(flt(doc.grand_total) / flt(doc.conversion_rate)), 2);
-	doc.rounded_total_import = Math.round(doc.grand_total_import);
-
-	refresh_many(['net_total','total_taxes','grand_total']);
-
-
-	if(doc.doctype == 'Purchase Invoice'){
-		calculate_outstanding(doc);
-	}
-}
-
-var calculate_outstanding = function(doc) {
-	// total amount to pay	
-	doc.total_amount_to_pay = flt(doc.grand_total) - flt(doc.write_off_amount);
-	
-	// outstanding amount 
-	if(doc.docstatus==0) doc.outstanding_amount = doc.total_amount_to_pay - flt(doc.total_advance);
-	
-	refresh_many(['total_amount_to_pay', 'outstanding_amount']);
-}
-
-
-cur_frm.cscript.project_name = function(doc, cdt, cdn) {
-	var item_doc = locals[cdt][cdn];
-	if (item_doc.project_name) {
-		$.each(getchildren(cur_frm.cscript.tname, doc.name, cur_frm.cscript.fname, doc.doctype),
-			function(i, v) {
-				if (v && !v.project_name) v.project_name = item_doc.project_name;
-			});
-		refresh_field(cur_frm.cscript.fname);
-	}
-}
-
-cur_frm.fields_dict.supplier && (cur_frm.fields_dict.supplier.get_query = erpnext.utils.supplier_query);
\ No newline at end of file
diff --git a/buying/doctype/purchase_common/purchase_common.py b/buying/doctype/purchase_common/purchase_common.py
index 7945954..fbda873 100644
--- a/buying/doctype/purchase_common/purchase_common.py
+++ b/buying/doctype/purchase_common/purchase_common.py
@@ -436,28 +436,4 @@
 		for d in getlist(obj.doclist, obj.fname):
 			if d.prevdoc_doctype and d.prevdoc_docname:
 				dt = sql("select transaction_date from `tab%s` where name = '%s'" % (d.prevdoc_doctype, d.prevdoc_docname))
-				d.prevdoc_date = dt and dt[0][0].strftime('%Y-%m-%d') or ''
-
-@webnotes.whitelist()
-def get_uom_details(args=None):
-	"""fetches details on change of UOM"""
-	if not args:
-		return {}
-		
-	if isinstance(args, basestring):
-		import json
-		args = json.loads(args)
-
-	uom = webnotes.conn.sql("""select conversion_factor
-		from `tabUOM Conversion Detail` where parent = %s and uom = %s""", 
-		(args['item_code'], args['uom']), as_dict=1)
-
-	if not uom: return {}
-
-	conversion_factor = args.get("conversion_factor") or \
-		flt(uom[0]["conversion_factor"])
-	
-	return {
-		"conversion_factor": conversion_factor,
-		"qty": flt(args["stock_qty"]) / conversion_factor,
-	}
+				d.prevdoc_date = dt and dt[0][0].strftime('%Y-%m-%d') or ''
\ No newline at end of file
diff --git a/buying/doctype/purchase_order/purchase_order.js b/buying/doctype/purchase_order/purchase_order.js
index ad2db91..64aa913 100644
--- a/buying/doctype/purchase_order/purchase_order.js
+++ b/buying/doctype/purchase_order/purchase_order.js
@@ -21,8 +21,8 @@
 cur_frm.cscript.other_fname = "purchase_tax_details";
 
 wn.require('app/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js');
-wn.require('app/buying/doctype/purchase_common/purchase_common.js');
 wn.require('app/utilities/doctype/sms_control/sms_control.js');
+wn.require('app/buying/doctype/purchase_common/purchase_common.js');
 
 erpnext.buying.PurchaseOrderController = erpnext.buying.BuyingController.extend({
 	refresh: function(doc, cdt, cdn) {
@@ -41,10 +41,8 @@
 	},
 });
 
-var new_cscript = new erpnext.buying.PurchaseOrderController({frm: cur_frm});
-
 // for backward compatibility: combine new and previous states
-$.extend(cur_frm.cscript, new_cscript);
+$.extend(cur_frm.cscript, new erpnext.buying.PurchaseOrderController({frm: cur_frm}));
 
 cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
 	if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
diff --git a/buying/doctype/supplier_quotation/supplier_quotation.js b/buying/doctype/supplier_quotation/supplier_quotation.js
index 4e5b62b..20a20ac 100644
--- a/buying/doctype/supplier_quotation/supplier_quotation.js
+++ b/buying/doctype/supplier_quotation/supplier_quotation.js
@@ -33,10 +33,8 @@
 	},	
 });
 
-var new_cscript = new erpnext.buying.SupplierQuotationController({frm: cur_frm});
-
 // for backward compatibility: combine new and previous states
-$.extend(cur_frm.cscript, new_cscript);
+$.extend(cur_frm.cscript, new erpnext.buying.SupplierQuotationController({frm: cur_frm}));
 
 cur_frm.cscript.make_purchase_order = function() {
 	var new_po_name = wn.model.make_new_doc_and_get_name("Purchase Order");
@@ -51,15 +49,6 @@
 	}, function(r, rt) { loaddoc("Purchase Order", new_po_name) });
 }
 
-cur_frm.cscript.supplier = function(doc, dt, dn) {
-	if (doc.supplier) {
-		get_server_fields('get_default_supplier_address',
-			JSON.stringify({ supplier: doc.supplier }), '', doc, dt, dn, 1,
-			function() { cur_frm.refresh(); });
-		cur_frm.cscript.toggle_contact_section(doc);
-	}
-}
-
 cur_frm.cscript.uom = function(doc, cdt, cdn) {
 	// no need to trigger updation of stock uom, as this field doesn't exist in supplier quotation
 }
diff --git a/buying/utils.py b/buying/utils.py
index 2c29e2c..1aaa5d1 100644
--- a/buying/utils.py
+++ b/buying/utils.py
@@ -52,8 +52,7 @@
 	out.supplier_part_no = _get_supplier_part_no(args, item_bean)
 	
 	if out.warehouse:
-		out.projected_qty = webnotes.conn.get_value("Bin", {"item_code": item.name, 
-			"warehouse": out.warehouse}, "projected_qty")
+		out.projected_qty = get_projected_qty(item.name, out.warehouse)
 	
 	if args.transaction_date and item.lead_time_days:
 		out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
@@ -92,7 +91,7 @@
 	
 	return out
 	
-def _get_price_list_rate(args, item_bean, meta=None):
+def _get_price_list_rate(args, item_bean, meta):
 	from utilities.transaction_base import validate_currency
 	item = item_bean.doc
 	out = webnotes._dict()
@@ -105,15 +104,16 @@
 			"ref_currency": args.price_list_currency,
 			"buying": 1})
 		if price_list_rate:
-			out.purchase_ref_rate = flt(price_list_rate[0].ref_rate) * flt(args.plc_conversion_rate)
+			out.import_ref_rate = \
+				flt(price_list_rate[0].ref_rate * args.plc_conversion_rate / args.conversion_rate)
 		
 	# if not found, fetch from last purchase transaction
-	if not out.purchase_ref_rate:
+	if not out.import_ref_rate:
 		last_purchase = get_last_purchase_details(item.name, args.docname, args.conversion_rate)
 		if last_purchase:
 			out.update(last_purchase)
 	
-	if out.purchase_ref_rate or out.purchase_rate or out.rate:
+	if out.import_ref_rate or out.import_rate:
 		validate_currency(args, item, meta)
 	
 	return out
@@ -198,4 +198,14 @@
 		"rate": out.purchase_rate
 	})
 	
-	return out
\ No newline at end of file
+	return out
+	
+@webnotes.whitelist()
+def get_conversion_factor(item_code, uom):
+	return {"conversion_factor": webnotes.conn.get_value("UOM Conversion Detail",
+		{"parent": item_code, "uom": uom})}
+		
+@webnotes.whitelist()
+def get_projected_qty(item_code, warehouse):
+	return webnotes.conn.get_value("Bin", {"item_code": item_code, 
+			"warehouse": warehouse}, "projected_qty")
\ No newline at end of file
diff --git a/controllers/selling_controller.py b/controllers/selling_controller.py
index de90fa7..d5399a4 100644
--- a/controllers/selling_controller.py
+++ b/controllers/selling_controller.py
@@ -48,6 +48,9 @@
 	def set_customer_defaults(self):
 		self.get_default_customer_address()
 		
+		if self.meta.get_field("shipping_address"):
+			self.doc.fields.update(self.get_shipping_address(self.doc.customer))
+		
 	def set_total_in_words(self):
 		from webnotes.utils import money_in_words
 		company_currency = get_company_currency(self.doc.company)
diff --git a/public/js/transaction.js b/public/js/transaction.js
index 34e10f6..86fe69a 100644
--- a/public/js/transaction.js
+++ b/public/js/transaction.js
@@ -24,16 +24,17 @@
 				currency = wn.defaults.get_default("currency");
 			
 			$.each({
-				"posting_date": today,
-				"due_date": today,
-				"transaction_date": today,
-				"currency": currency,
-				"price_list_currency": currency,
-				"status": "Draft",
-				"fiscal_year": wn.defaults.get_default("fiscal_year"),
-				"is_subcontracted": "No",
-				"conversion_rate": 1.0,
-				"plc_conversion_rate": 1.0
+				posting_date: today,
+				due_date: today,
+				transaction_date: today,
+				currency: currency,
+				price_list_currency: currency,
+				status: "Draft",
+				company: wn.defaults.get_default("company"),
+				fiscal_year: wn.defaults.get_default("fiscal_year"),
+				is_subcontracted: "No",
+				conversion_rate: 1.0,
+				plc_conversion_rate: 1.0
 			}, function(fieldname, value) {
 				if(me.frm.fields_dict[fieldname] && !me.frm.doc[fieldname])
 					me.frm.set_value(fieldname, value);
@@ -434,6 +435,18 @@
 			tax.item_wise_tax_detail = JSON.stringify(tax.item_wise_tax_detail);
 		});
 	},
+
+	calculate_total_advance: function(parenttype, advance_parentfield) {
+		if(this.frm.doc.doctype == parenttype && this.frm.doc.docstatus < 2) {
+			var advance_doclist = wn.model.get_doclist(this.frm.doc.doctype, this.frm.doc.name, 
+				{parentfield: advance_parentfield});
+			this.frm.doc.total_advance = flt(wn.utils.sum(
+				$.map(advance_doclist, function(adv) { return adv.allocated_amount })
+			), precision("total_advance"));
+			
+			this.calculate_outstanding_amount();
+		}
+	},
 	
 	_set_in_company_currency: function(item, print_field, base_field) {
 		// set values in base currency
diff --git a/selling/doctype/quotation/quotation.js b/selling/doctype/quotation/quotation.js
index a7c5421..db45672 100644
--- a/selling/doctype/quotation/quotation.js
+++ b/selling/doctype/quotation/quotation.js
@@ -21,101 +21,40 @@
 cur_frm.cscript.sales_team_fname = "sales_team";
 
 // =====================================================================================
-wn.require('app/selling/doctype/sales_common/sales_common.js');
 wn.require('app/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js');
 wn.require('app/utilities/doctype/sms_control/sms_control.js');
+wn.require('app/selling/doctype/sales_common/sales_common.js');
 
-// ONLOAD
-// ===================================================================================
-cur_frm.cscript.onload = function(doc, cdt, cdn) {
-	cur_frm.cscript.manage_rounded_total();
-	if(!doc.quotation_to) 
-		hide_field(['customer','customer_address','contact_person','customer_name','lead', 
-	 		'address_display', 'contact_display', 'contact_mobile', 'contact_email', 
-			'territory', 'customer_group']);
-	if(!doc.price_list_name) set_multiple(cdt,cdn,{price_list_name:sys_defaults.price_list_name});
-	if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
-	if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
-	if(!doc.conversion_rate) set_multiple(cdt,cdn,{conversion_rate:'1.00'});
-	if(!doc.currency && sys_defaults.currency) set_multiple(cdt,cdn,{currency:sys_defaults.currency});
-	if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
-
-	if(!doc.company && sys_defaults.company) set_multiple(cdt,cdn,{company:sys_defaults.company});
-	if(!doc.fiscal_year && sys_defaults.fiscal_year) set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});
-	
-	if(doc.quotation_to) {
-		if(doc.quotation_to == 'Customer') {
-			hide_field('lead');
+erpnext.selling.QuotationController = erpnext.selling.SellingController.extend({
+	refresh: function(doc, dt, dn) {
+		this._super();
+		
+		if(doc.docstatus == 1 && doc.status!='Order Lost') {
+			cur_frm.add_custom_button('Make Sales Order', cur_frm.cscript['Make Sales Order']);
+			cur_frm.add_custom_button('Set as Lost', cur_frm.cscript['Declare Order Lost']);
+			cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
 		}
-		else if (doc.quotation_to == 'Lead') {
-			hide_field(['customer', 'customer_address', 'contact_person', 'customer_group']);
+
+		if (!doc.__islocal) {
+			cur_frm.communication_view = new wn.views.CommunicationList({
+				list: wn.model.get("Communication", {"quotation": doc.name}),
+				parent: cur_frm.fields_dict.communication_html.wrapper,
+				doc: doc,
+				recipients: doc.contact_email
+			});		
 		}
-	}
-}
-
-// hide - unhide fields based on lead or customer..
-// =======================================================================================================================
-cur_frm.cscript.lead_cust_show = function(doc,cdt,cdn){
-	hide_field(['lead', 'customer','customer_address','contact_person',
-		'customer_name','address_display','contact_display','contact_mobile','contact_email',
-		'territory','customer_group']);
-	if(doc.quotation_to == 'Lead') unhide_field(['lead']);
-	else if(doc.quotation_to == 'Customer') unhide_field(['customer']);
+		
+		this.quotation_to();
+	},
 	
-	doc.lead = doc.customer = doc.customer_name = doc.customer_address = doc.contact_person = doc.address_display = doc.contact_display = doc.contact_mobile = doc.contact_email = doc.territory = doc.customer_group = "";
-}
+	quotation_to: function() {
+		this.frm.toggle_reqd("lead", this.frm.doc.quotation_to == "Lead");
+		this.frm.toggle_reqd("customer", this.frm.doc.quotation_to == "Customer");
+	},
+});
 
-
-
-//================ hide - unhide fields on basis of quotation to either lead or customer ===============================
-cur_frm.cscript.quotation_to = function(doc,cdt,cdn){
-	cur_frm.cscript.lead_cust_show(doc,cdt,cdn);
-}
-
-
-// REFRESH
-// ===================================================================================
-cur_frm.cscript.refresh = function(doc, cdt, cdn) {
-	cur_frm.clear_custom_buttons();
-
-	if (!cur_frm.cscript.is_onload) cur_frm.cscript.hide_price_list_currency(doc, cdt, cdn); 
-
-
-	if(doc.docstatus == 1 && doc.status!='Order Lost') {
-		cur_frm.add_custom_button('Make Sales Order', cur_frm.cscript['Make Sales Order']);
-		cur_frm.add_custom_button('Set as Lost', cur_frm.cscript['Declare Order Lost']);
-		cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
-	}
-
-	erpnext.hide_naming_series();
-	cur_frm.toggle_display("contact_section", doc.customer || doc.lead);
-	
-	if (!doc.__islocal) {
-		cur_frm.communication_view = new wn.views.CommunicationList({
-			list: wn.model.get("Communication", {"quotation": doc.name}),
-			parent: cur_frm.fields_dict.communication_html.wrapper,
-			doc: doc,
-			recipients: doc.contact_email
-		});		
-	}
-}
-
-
-//customer
-cur_frm.cscript.customer = function(doc,dt,dn) {
-	var pl = doc.price_list_name;
-	var callback = function(r,rt) {
-		var doc = locals[cur_frm.doctype][cur_frm.docname];
-		cur_frm.refresh();		
-		if (pl != doc.price_list_name) cur_frm.cscript.price_list_name(doc, dt, dn); 
-	}
-
-	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 
-		'get_default_customer_address', '', callback);
-	if(doc.customer) unhide_field(['customer_address','contact_person','territory', 'customer_group']);
-	cur_frm.toggle_display("contact_section", doc.customer || doc.lead);
-		console.log(doc.customer_group);
-}
+// for backward compatibility: combine new and previous states
+$.extend(cur_frm.cscript, new erpnext.selling.QuotationController({frm: cur_frm}));
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({
@@ -240,31 +179,6 @@
 	qtn_lost_dialog.show();
 }
 
-//===================== Quotation to validation - either customer or lead mandatory ====================
-cur_frm.cscript.quot_to_validate = function(doc,cdt,cdn){
-
-	if(doc.quotation_to == 'Lead'){
-
-		if(!doc.lead){
-			alert("Lead is mandatory.");
-			validated = false;
-		}
-	}
-	else if(doc.quotation_to == 'Customer'){
-		if(!doc.customer){
-			alert("Customer is mandatory.");
-			validated = false;
-		}
-	}
-}
-
-//===================validation function =================================
-
-cur_frm.cscript.validate = function(doc,cdt,cdn){
-	cur_frm.cscript.recalculate_values(doc, cdt, cdn);
-	cur_frm.cscript.quot_to_validate(doc,cdt,cdn);
-}
-
 //================ Last Quoted Price and Last Sold Price suggestion ======================
 cur_frm.fields_dict['quotation_details'].grid.get_field('item_code').get_query= function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];
diff --git a/selling/doctype/sales_common/sales_common.js b/selling/doctype/sales_common/sales_common.js
index 4d97034..828d3d3 100644
--- a/selling/doctype/sales_common/sales_common.js
+++ b/selling/doctype/sales_common/sales_common.js
@@ -182,6 +182,20 @@
 		}
 	},
 	
+	warehouse: function(doc, cdt, cdn) {
+		var item = webnotes.get_doc(cdt, cdn);
+		if(item.item_code && (item.warehouse || item.reserved_warehouse)) {
+			this.frm.call({
+				method: "selling.utils.get_available_qty",
+				child: item,
+				args: {
+					item_code: item.item_code,
+					warehouse: item.warehouse || item.reserved_warehouse,
+				},
+			});
+		}
+	},
+	
 	toggle_rounded_total: function() {
 		var me = this;
 		if(cint(wn.defaults.get_global_default("disable_rounded_total"))) {
@@ -194,6 +208,7 @@
 	
 	calculate_taxes_and_totals: function() {
 		this._super();
+		this.calculate_total_advance();
 		this.calculate_commission();
 		this.calculate_contribution();
 		
@@ -310,6 +325,23 @@
 		this.frm.doc.rounded_total_export = Math.round(this.frm.doc.grand_total_export);
 	},
 	
+	calculate_total_advance: function() {
+		this._super("Sales Invoice", "advance_adjustment_details");
+	},
+	
+	calculate_outstanding_amount: function() {
+		// TODO - I find this incorrect!
+		// see TODO of sales invoice.js / write_off_outstanding_amount_automatically
+		
+		if(this.frm.doc.doctype == "Sales Invoice" && this.frm.doc.docstatus < 2) {
+			wn.model.round_floats_in(this.frm.doc, ["grand_total", "total_advance", "write_off_amount",
+				"paid_amount"]);
+			var total_amount_to_pay = this.frm.doc.grand_total - this.frm.doc.write_off_amount;
+			this.frm.doc.outstanding_amount = flt(total_amount_to_pay - this.frm.doc.total_advance - 
+				this.frm.doc.paid_amount, precision("outstanding_amount"));
+		}
+	},
+	
 	calculate_commission: function() {
 		if(this.frm.doc.commission_rate > 100) {
 			var msg = wn._(wn.meta.get_label(this.frm.doc.doctype, "commission_rate", this.frm.doc.name)) +
diff --git a/selling/doctype/sales_common/sales_common.py b/selling/doctype/sales_common/sales_common.py
index 0ac8031..5b391bb 100644
--- a/selling/doctype/sales_common/sales_common.py
+++ b/selling/doctype/sales_common/sales_common.py
@@ -48,26 +48,6 @@
 
 		self.msg = []
 
-
-	# Get Sales Person Details
-	# ==========================
-	
-	# TODO: To be deprecated if not in use
-	def get_sales_person_details(self, obj):
-		if obj.doc.doctype != 'Quotation':
-			obj.doclist = obj.doc.clear_table(obj.doclist,'sales_team')
-			idx = 0
-			for d in webnotes.conn.sql("select sales_person, allocated_percentage, allocated_amount, incentives from `tabSales Team` where parent = '%s'" % obj.doc.customer):
-				ch = addchild(obj.doc, 'sales_team', 'Sales Team', obj.doclist)
-				ch.sales_person = d and cstr(d[0]) or ''
-				ch.allocated_percentage = d and flt(d[1]) or 0
-				ch.allocated_amount = d and flt(d[2]) or 0
-				ch.incentives = d and flt(d[3]) or 0
-				ch.idx = idx
-				idx += 1
-		return obj.doclist
-
-
 	# Get customer's contact person details
 	# ==============================================================
 	def get_contact_details(self, obj = '', primary = 0):
@@ -100,161 +80,6 @@
 		if obj.doc.company:
 			acc_head = webnotes.conn.sql("select name from `tabAccount` where name = '%s' and docstatus != 2" % (cstr(obj.doc.customer) + " - " + webnotes.conn.get_value('Company', obj.doc.company, 'abbr')))
 			obj.doc.debit_to = acc_head and acc_head[0][0] or ''
-
-	
-	
-	# Get Item Details
-	# ===============================================================
-	# def get_item_details(self, args, obj):
-	# 	import json
-	# 	if not obj.doc.price_list_name:
-	# 		msgprint("Please Select Price List before selecting Items", raise_exception=True)
-	# 	item = webnotes.conn.sql("""select description, item_name, brand, item_group, stock_uom, 
-	# 		default_warehouse, default_income_account, default_sales_cost_center, 
-	# 		purchase_account, description_html, barcode from `tabItem` 
-	# 		where name = %s and (ifnull(end_of_life,'')='' or end_of_life >	now() 
-	# 		or end_of_life = '0000-00-00') and (is_sales_item = 'Yes' 
-	# 		or is_service_item = 'Yes')""", args['item_code'], as_dict=1)
-	# 	tax = webnotes.conn.sql("""select tax_type, tax_rate from `tabItem Tax` 
-	# 		where parent = %s""", args['item_code'])
-	# 	t = {}
-	# 	for x in tax: t[x[0]] = flt(x[1])
-	# 	ret = {
-	# 		'description': item and item[0]['description_html'] or \
-	# 			item[0]['description'],
-	# 		'barcode': item and item[0]['barcode'] or '',
-	# 		'item_group': item and item[0]['item_group'] or '',
-	# 		'item_name': item and item[0]['item_name'] or '',
-	# 		'brand': item and item[0]['brand'] or '',
-	# 		'stock_uom': item and item[0]['stock_uom'] or '',
-	# 		'reserved_warehouse': item and item[0]['default_warehouse'] or '',
-	# 		'warehouse': item and item[0]['default_warehouse'] or \
-	# 			args.get('warehouse'),
-	# 		'income_account': item and item[0]['default_income_account'] or \
-	# 			args.get('income_account'),
-	# 		'expense_account': item and item[0]['purchase_account'] or \
-	# 		 	args.get('expense_account'),
-	# 		'cost_center': item and item[0]['default_sales_cost_center'] or \
-	# 			args.get('cost_center'),
-	# 		# this is done coz if item once fetched is fetched again than its qty shld be reset to 1
-	# 		'qty': 1.00, 
-	# 		'adj_rate': 0,
-	# 		'amount': 0,
-	# 		'export_amount': 0,
-	# 		'item_tax_rate': json.dumps(t),
-	# 		'batch_no': ''
-	# 	}
-	# 	if(obj.doc.price_list_name and item):	#this is done to fetch the changed BASIC RATE and REF RATE based on PRICE LIST
-	# 		base_ref_rate =	self.get_ref_rate(args['item_code'], obj.doc.price_list_name, obj.doc.price_list_currency, obj.doc.plc_conversion_rate)
-	# 		ret['ref_rate'] = flt(base_ref_rate)/flt(obj.doc.conversion_rate)
-	# 		ret['export_rate'] = flt(base_ref_rate)/flt(obj.doc.conversion_rate)
-	# 		ret['base_ref_rate'] = flt(base_ref_rate)
-	# 		ret['basic_rate'] = flt(base_ref_rate)
-	# 		
-	# 	if ret['warehouse'] or ret['reserved_warehouse']:
-	# 		av_qty = self.get_available_qty({'item_code': args['item_code'], 'warehouse': ret['warehouse'] or ret['reserved_warehouse']})
-	# 		ret.update(av_qty)
-	# 		
-	# 	# get customer code for given item from Item Customer Detail
-	# 	customer_item_code_row = webnotes.conn.sql("""\
-	# 		select ref_code from `tabItem Customer Detail`
-	# 		where parent = %s and customer_name = %s""",
-	# 		(args['item_code'], obj.doc.customer))
-	# 	if customer_item_code_row and customer_item_code_row[0][0]:
-	# 		ret['customer_item_code'] = customer_item_code_row[0][0]
-	# 	
-	# 	return ret
-
-	# TODO: deprecate it
-	def get_item_defaults(self, args):
-		item = webnotes.conn.sql("""select default_warehouse, default_income_account, 
-			default_sales_cost_center, purchase_account from `tabItem` where name = %s 
-			and (ifnull(end_of_life,'') = '' or end_of_life > now() or end_of_life = '0000-00-00') 
-			and (is_sales_item = 'Yes' or is_service_item = 'Yes') """, 
-			(args['item_code']), as_dict=1)
-		ret = {
-			'reserved_warehouse': item and item[0]['default_warehouse'] or '',
-			'warehouse': item and item[0]['default_warehouse'] or args.get('warehouse'),
-			'income_account': item and item[0]['default_income_account'] or \
-				args.get('income_account'),
-			'expense_account': item and item[0]['purchase_account'] or args.get('expense_account'),
-			'cost_center': item and item[0]['default_sales_cost_center'] or args.get('cost_center'),
-		}
-
-		return ret
-
-	# def get_available_qty(self,args):
-# 		tot_avail_qty = webnotes.conn.sql("select projected_qty, actual_qty from `tabBin` where item_code = '%s' and warehouse = '%s'" % (args['item_code'], args['warehouse']), as_dict=1)
-# 		ret = {
-# 			 'projected_qty' : tot_avail_qty and flt(tot_avail_qty[0]['projected_qty']) or 0,
-# 			 'actual_qty' : tot_avail_qty and flt(tot_avail_qty[0]['actual_qty']) or 0
-# 		}
-# 		return ret
-
-	
-	# ***************** Get Ref rate as entered in Item Master ********************
-	# def get_ref_rate(self, item_code, price_list_name, price_list_currency, plc_conv_rate):
-	# 	ref_rate = webnotes.conn.sql("select ref_rate from `tabItem Price` where parent = %s and price_list_name = %s and ref_currency = %s and selling=1", 
-	# 	(item_code, price_list_name, price_list_currency))
-	# 	base_ref_rate = ref_rate and flt(ref_rate[0][0]) * flt(plc_conv_rate) or 0
-	# 	return base_ref_rate
-
-	# ****** Re-cancellculates Basic Rate & amount based on Price List Selected ******
-	# def get_adj_percent(self, obj): 
-	# 	for d in getlist(obj.doclist, obj.fname):
-	# 		base_ref_rate = self.get_ref_rate(d.item_code, obj.doc.price_list_name, obj.doc.price_list_currency, obj.doc.plc_conversion_rate)
-	# 		d.adj_rate = 0
-	# 		d.ref_rate = flt(base_ref_rate)/flt(obj.doc.conversion_rate)
-	# 		d.basic_rate = flt(base_ref_rate)
-	# 		d.base_ref_rate = flt(base_ref_rate)
-	# 		d.export_rate = flt(base_ref_rate)/flt(obj.doc.conversion_rate)
-	# 		d.amount = flt(d.qty)*flt(base_ref_rate)
-	# 		d.export_amount = flt(d.qty)*flt(base_ref_rate)/flt(obj.doc.conversion_rate)
-
-
-	# # Load Default Taxes
-	# # ====================
-	# def load_default_taxes(self, obj):
-	# 	if cstr(obj.doc.charge):
-	# 		return self.get_other_charges(obj)
-	# 	else:
-	# 		return self.get_other_charges(obj, 1)
-	# 
-	# 	
-	# # Get other charges from Master
-	# # =================================================================================
-	# def get_other_charges(self,obj, default=0):
-	# 	obj.doclist = obj.doc.clear_table(obj.doclist, 'other_charges')
-	# 	if not getlist(obj.doclist, 'other_charges'):
-	# 		if default: add_cond = 'ifnull(t2.is_default,0) = 1'
-	# 		else: add_cond = 't1.parent = "'+cstr(obj.doc.charge)+'"'
-	# 		idx = 0
-	# 		other_charge = webnotes.conn.sql("""\
-	# 			select t1.*
-	# 			from
-	# 				`tabSales Taxes and Charges` t1,
-	# 				`tabSales Taxes and Charges Master` t2
-	# 			where
-	# 				t1.parent = t2.name and
-	# 				t2.company = '%s' and
-	# 				%s
-	# 			order by t1.idx""" % (obj.doc.company, add_cond), as_dict=1)
-	# 		from webnotes.model import default_fields
-	# 		for other in other_charge:
-	# 			# remove default fields like parent, parenttype etc.
-	# 			# from query results
-	# 			for field in default_fields:
-	# 				if field in other: del other[field]
-	# 
-	# 			d = addchild(obj.doc, 'other_charges', 'Sales Taxes and Charges',
-	# 				obj.doclist)
-	# 			d.fields.update(other)
-	# 			d.rate = flt(d.rate)
-	# 			d.tax_amount = flt(d.tax_rate)
-	# 			d.included_in_print_rate = cint(d.included_in_print_rate)
-	# 			d.idx = idx
-	# 			idx += 1
-	# 	return obj.doclist
 			
 	# Get TERMS AND CONDITIONS
 	# =======================================================================================
diff --git a/selling/doctype/sales_order/sales_order.js b/selling/doctype/sales_order/sales_order.js
index 79f20bc..ded9c44 100644
--- a/selling/doctype/sales_order/sales_order.js
+++ b/selling/doctype/sales_order/sales_order.js
@@ -26,90 +26,54 @@
 wn.require('app/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js');
 wn.require('app/utilities/doctype/sms_control/sms_control.js');
 
-
-cur_frm.cscript.onload = function(doc, cdt, cdn) {
-	cur_frm.cscript.toggle_rounded_total();
-	
-	if(!doc.status) set_multiple(cdt,cdn,{status:'Draft'});
-	if(!doc.transaction_date) set_multiple(cdt,cdn,{transaction_date:get_today()});
-	if(!doc.price_list_currency) set_multiple(cdt, cdn, {price_list_currency: doc.currency, plc_conversion_rate: 1});
-	// load default charges
-	
-	if(doc.__islocal && !doc.customer){
-		hide_field(['customer_address','contact_person', 'customer_name', 
-			'address_display', 'contact_display', 'contact_mobile', 
-			'contact_email', 'territory',  'customer_group']);
-	}
-}
-
-cur_frm.cscript.refresh = function(doc, cdt, cdn) {
-	cur_frm.clear_custom_buttons();
-	erpnext.hide_naming_series();
-
-	cur_frm.toggle_display("contact_info", doc.customer);
-	
-	if(doc.docstatus==1) {
-		if(doc.status != 'Stopped') {
-			cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
-			// delivery note
-			if(flt(doc.per_delivered, 2) < 100 && doc.order_type=='Sales')
-				cur_frm.add_custom_button('Make Delivery', cur_frm.cscript['Make Delivery Note']);
+erpnext.selling.SalesOrderController = erpnext.selling.SellingController.extend({
+	refresh: function(doc, dt, dn) {
+		this._super();
+		
+		if(doc.docstatus==1) {
+			if(doc.status != 'Stopped') {
+				cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
+				// delivery note
+				if(flt(doc.per_delivered, 2) < 100 && doc.order_type=='Sales')
+					cur_frm.add_custom_button('Make Delivery', cur_frm.cscript['Make Delivery Note']);
 			
-			// maintenance
-			if(flt(doc.per_delivered, 2) < 100 && (doc.order_type !='Sales')) {
-				cur_frm.add_custom_button('Make Maint. Visit', cur_frm.cscript.make_maintenance_visit);
-				cur_frm.add_custom_button('Make Maint. Schedule', cur_frm.cscript['Make Maintenance Schedule']);
+				// maintenance
+				if(flt(doc.per_delivered, 2) < 100 && (doc.order_type !='Sales')) {
+					cur_frm.add_custom_button('Make Maint. Visit', cur_frm.cscript.make_maintenance_visit);
+					cur_frm.add_custom_button('Make Maint. Schedule', cur_frm.cscript['Make Maintenance Schedule']);
+				}
+
+				// indent
+				if(!doc.order_type || (doc.order_type == 'Sales'))
+					cur_frm.add_custom_button('Make ' + wn._('Material Request'), cur_frm.cscript['Make Material Request']);
+			
+				// sales invoice
+				if(flt(doc.per_billed, 2) < 100)
+					cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
+			
+				// stop
+				if(flt(doc.per_delivered, 2) < 100 || doc.per_billed < 100)
+					cur_frm.add_custom_button('Stop!', cur_frm.cscript['Stop Sales Order']);
+			} else {	
+				// un-stop
+				cur_frm.add_custom_button('Unstop', cur_frm.cscript['Unstop Sales Order']);
 			}
-
-			// indent
-			if(!doc.order_type || (doc.order_type == 'Sales'))
-				cur_frm.add_custom_button('Make ' + wn._('Material Request'), cur_frm.cscript['Make Material Request']);
-			
-			// sales invoice
-			if(flt(doc.per_billed, 2) < 100)
-				cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
-			
-			// stop
-			if(flt(doc.per_delivered, 2) < 100 || doc.per_billed < 100)
-				cur_frm.add_custom_button('Stop!', cur_frm.cscript['Stop Sales Order']);
-		} else {	
-			// un-stop
-			cur_frm.add_custom_button('Unstop', cur_frm.cscript['Unstop Sales Order']);
 		}
-	}
 	
-	cur_frm.cscript.order_type(doc);
-}
-
-cur_frm.cscript.order_type = function(doc) {
-	if(doc.order_type == "Sales") {
-		cur_frm.toggle_reqd("delivery_date", 1);
-	} else {
-		cur_frm.toggle_reqd("delivery_date", 0);
-	}
-}
-
-//customer
-cur_frm.cscript.customer = function(doc,dt,dn) {
-	cur_frm.toggle_display("contact_info", doc.customer);
+		this.order_type(doc);
+	},
 	
-	var pl = doc.price_list_name;
-	var callback = function(r,rt) {
-		var callback2  = function(r, rt) {
-			if(doc.customer) 
-				unhide_field(['customer_address', 'contact_person', 'territory','customer_group']);
-			cur_frm.refresh();
-			
-			if(!onload && (pl != doc.price_list_name)) cur_frm.cscript.price_list_name(doc, dt, dn);
+	order_type: function() {
+		this.frm.toggle_reqd("delivery_date", this.frm.doc.order_type == "Sales");
+	},
+	
+	reserved_warehouse: function(doc, cdt, cdn) {
+		this.warehouse(doc, cdt, cdn);
+	},
+});
 
-		}
-		var doc = locals[cur_frm.doctype][cur_frm.docname];
-		get_server_fields('get_shipping_address',doc.customer,'',doc, dt, dn, 0, callback2);
-			
-	}	 
-	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name), 
-		'get_default_customer_address', '', callback);
-}
+// for backward compatibility: combine new and previous states
+$.extend(cur_frm.cscript, new erpnext.selling.SalesOrderController({frm: cur_frm}));
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
@@ -165,15 +129,6 @@
 			ORDER BY `tabQuotation`.`name` DESC LIMIT 50', {cond:cond});
 }
 
-
-cur_frm.cscript.reserved_warehouse = function(doc, cdt , cdn) {
-	var d = locals[cdt][cdn];
-	if (d.reserved_warehouse) {
-		arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.reserved_warehouse +"'}";
-		get_server_fields('get_available_qty',arg,'sales_order_details',doc,cdt,cdn,1);
-	}
-}
-
 //----------- make maintenance schedule----------
 cur_frm.cscript['Make Maintenance Schedule'] = function() {
 	var doc = cur_frm.doc;
diff --git a/selling/doctype/sales_order/sales_order.py b/selling/doctype/sales_order/sales_order.py
index 4b5408d..79b37be 100644
--- a/selling/doctype/sales_order/sales_order.py
+++ b/selling/doctype/sales_order/sales_order.py
@@ -58,22 +58,6 @@
 	def get_comm_rate(self, sales_partner):
 		return get_obj('Sales Common').get_comm_rate(sales_partner, self)
 
-	def get_item_details(self, args=None):
-		import json
-		args = args and json.loads(args) or {}
-		if args.get('item_code'):
-			return get_obj('Sales Common').get_item_details(args, self)
-		else:
-			obj = get_obj('Sales Common')
-			for doc in self.doclist:
-				if doc.fields.get('item_code'):
-					arg = {'item_code':doc.fields.get('item_code'), 'income_account':doc.fields.get('income_account'), 
-						'cost_center': doc.fields.get('cost_center'), 'warehouse': doc.fields.get('warehouse')};
-					ret = obj.get_item_defaults(arg)
-					for r in ret:
-						if not doc.fields.get(r):
-							doc.fields[r] = ret[r]					
-
 	def get_adj_percent(self, arg=''):
 		get_obj('Sales Common').get_adj_percent(self)
 
diff --git a/selling/utils.py b/selling/utils.py
index 5e986ee..6901028 100644
--- a/selling/utils.py
+++ b/selling/utils.py
@@ -68,7 +68,7 @@
 			out.update(_get_price_list_rate(args, item_bean, meta))
 	
 	if out.warehouse or out.reserved_warehouse:
-		out.update(_get_available_qty(args, out.warehouse or out.reserved_warehouse))
+		out.update(get_available_qty(args.item_code, out.warehouse or out.reserved_warehouse))
 	
 	out.customer_item_code = _get_customer_item_code(args, item_bean)
 	
@@ -109,6 +109,7 @@
 def _get_basic_details(args, item_bean):
 	item = item_bean.doc
 	out = webnotes._dict({
+			"item_code": item.name,
 			"description": item.description_html or item.description,
 			"reserved_warehouse": item.default_warehouse,
 			"warehouse": item.default_warehouse or args.warehouse,
@@ -129,7 +130,7 @@
 			
 	return out
 	
-def _get_price_list_rate(args, item_bean, meta=None):
+def _get_price_list_rate(args, item_bean, meta):
 	base_ref_rate = item_bean.doclist.get({
 		"parentfield": "ref_rate_details",
 		"price_list_name": args.price_list_name, 
@@ -143,10 +144,11 @@
 	from utilities.transaction_base import validate_currency
 	validate_currency(args, item_bean.doc, meta)
 	
-	return {"base_ref_rate": flt(base_ref_rate[0].ref_rate / args.plc_conversion_rate)}
-	
-def _get_available_qty(args, warehouse):
-	return webnotes.conn.get_value("Bin", {"item_code": args.item_code, "warehouse": warehouse}, 
+	return {"ref_rate": flt(base_ref_rate[0].ref_rate * args.plc_conversion_rate / args.conversion_rate)}
+
+@webnotes.whitelist()
+def get_available_qty(item_code, warehouse):
+	return webnotes.conn.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, 
 		["projected_qty", "actual_qty"], as_dict=True) or {}
 		
 def _get_customer_item_code(args, item_bean):
@@ -173,6 +175,6 @@
 			out[fieldname] = pos_settings.get(fieldname)
 			
 	if out.get("warehouse"):
-		out["actual_qty"] = _get_available_qty(opts, out.get("warehouse")).get("actual_qty")
+		out["actual_qty"] = get_available_qty(opts.item_code, out.get("warehouse")).get("actual_qty")
 	
 	return out
diff --git a/stock/doctype/delivery_note/delivery_note.js b/stock/doctype/delivery_note/delivery_note.js
index df5e761..e1b23f0 100644
--- a/stock/doctype/delivery_note/delivery_note.js
+++ b/stock/doctype/delivery_note/delivery_note.js
@@ -20,75 +20,36 @@
 cur_frm.cscript.other_fname = "other_charges";
 cur_frm.cscript.sales_team_fname = "sales_team";
 
-wn.require('app/selling/doctype/sales_common/sales_common.js');
 wn.require('app/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.js');
 wn.require('app/utilities/doctype/sms_control/sms_control.js');
+wn.require('app/selling/doctype/sales_common/sales_common.js');
 
-// ONLOAD
-// ================================================================================================
-cur_frm.cscript.onload = function(doc, dt, dn) {
-	cur_frm.cscript.manage_rounded_total();
-	if(!doc.status) set_multiple(dt,dn,{status:'Draft'});
-	if(!doc.transaction_date) set_multiple(dt,dn,{transaction_date:get_today()});
-	if(!doc.posting_date) set_multiple(dt,dn,{posting_date:get_today()});
-	if(doc.__islocal && doc.customer) cur_frm.cscript.customer(doc,dt,dn,onload=true);
-	if(!doc.price_list_currency) {
-		set_multiple(dt, dn, {price_list_currency: doc.currency, plc_conversion_rate:1});
-	}
+wn.provide("erpnext.stock");
+erpnext.stock.DeliveryNoteController = erpnext.selling.SellingController.extend({
+	refresh: function(doc, dt, dn) {
+		this._super();
 		
-	if(doc.__islocal){
-		hide_field(['customer_address', 'contact_person', 'customer_name', 
-			'address_display', 'contact_display', 'contact_mobile', 
-			'contact_email', 'territory', 'customer_group']);
-	}	
-}
-
-// REFRESH
-// ================================================================================================
-cur_frm.cscript.refresh = function(doc, cdt, cdn) { 
-	cur_frm.clear_custom_buttons();
-	erpnext.hide_naming_series();
+		if(flt(doc.per_billed, 2) < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
 	
-	if (!cur_frm.cscript.is_onload) cur_frm.cscript.hide_price_list_currency(doc, cdt, cdn); 
+		if(flt(doc.per_installed, 2) < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Installation Note', cur_frm.cscript['Make Installation Note']);
 
- 
-	if(flt(doc.per_billed, 2) < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Invoice', cur_frm.cscript['Make Sales Invoice']);
+		if (doc.docstatus==1) cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
+
+		if(doc.docstatus==0 && !doc.__islocal) {
+			cur_frm.add_custom_button('Make Packing Slip', cur_frm.cscript['Make Packing Slip']);
+		}
 	
-	if(flt(doc.per_installed, 2) < 100 && doc.docstatus==1) cur_frm.add_custom_button('Make Installation Note', cur_frm.cscript['Make Installation Note']);
-
-	if (doc.docstatus==1) cur_frm.add_custom_button('Send SMS', cur_frm.cscript.send_sms);
-
-	if(doc.docstatus==0 && !doc.__islocal) {
-		cur_frm.add_custom_button('Make Packing Slip', cur_frm.cscript['Make Packing Slip']);
+		set_print_hide(doc, dt, dn);
+	
+		// unhide expense_account and cost_center is auto_inventory_accounting enabled
+		var aii_enabled = cint(sys_defaults.auto_inventory_accounting)
+		cur_frm.fields_dict[cur_frm.cscript.fname].grid.set_column_disp("expense_account", aii_enabled);
+		cur_frm.fields_dict[cur_frm.cscript.fname].grid.set_column_disp("cost_center", aii_enabled);
 	}
-	
-	cur_frm.toggle_display("contact_info", doc.customer);
-	
-	set_print_hide(doc, cdt, cdn);
-	
-	// unhide expense_account and cost_center is auto_inventory_accounting enabled
-	var aii_enabled = cint(sys_defaults.auto_inventory_accounting)
-	cur_frm.fields_dict[cur_frm.cscript.fname].grid.set_column_disp("expense_account", aii_enabled);
-	cur_frm.fields_dict[cur_frm.cscript.fname].grid.set_column_disp("cost_center", aii_enabled);
-}
+});
 
-
-//customer
-cur_frm.cscript.customer = function(doc,dt,dn,onload) {	
-	cur_frm.toggle_display("contact_info", doc.customer);
-	
-	var pl = doc.price_list_name;
-	var callback = function(r,rt) {
-			var doc = locals[cur_frm.doctype][cur_frm.docname];
-			if(doc.customer)
-			 	unhide_field(['customer_address','contact_person','territory','customer_group']);
-			cur_frm.refresh();
-			if(!onload && (pl != doc.price_list_name)) cur_frm.cscript.price_list_name(doc, dt, dn); 
-	} 
-	var args = onload ? 'onload':''
-	if(doc.customer) $c_obj(make_doclist(doc.doctype, doc.name),
-	 	'get_default_customer_shipping_address', args, callback);
-}
+// for backward compatibility: combine new and previous states
+$.extend(cur_frm.cscript, new erpnext.stock.DeliveryNoteController({frm: cur_frm}));
 
 cur_frm.cscript.customer_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
 	if(doc.customer) get_server_fields('get_customer_address', JSON.stringify({customer: doc.customer, address: doc.customer_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
@@ -148,11 +109,6 @@
 	return repl('SELECT DISTINCT `tabSales Order`.`name` FROM `tabSales Order` WHERE `tabSales Order`.company = "%(company)s" and `tabSales Order`.`docstatus` = 1 and `tabSales Order`.`status` != "Stopped" and ifnull(`tabSales Order`.per_delivered,0) < 99.99 and %(cond)s `tabSales Order`.%(key)s LIKE "%s" ORDER BY `tabSales Order`.`name` DESC LIMIT 50', {company:doc.company,cond:cond})
 }
 
-
-cur_frm.cscript.delivery_type = function(doc, cdt, cdn) {
-	if (doc.delivery_type = 'Sample') cfn_set_fields(doc, cdt, cdn);
-}
-
 cur_frm.cscript.serial_no = function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];
 	if (d.serial_no) {
@@ -160,17 +116,6 @@
 	}
 }
 
-
-cur_frm.cscript.warehouse = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	if (! d.item_code) {alert("please enter item code first"); return};
-	if (d.warehouse) {
-		arg = "{'item_code':'" + d.item_code + "','warehouse':'" + d.warehouse +"'}";
-		get_server_fields('get_actual_qty',arg,'delivery_note_details',doc,cdt,cdn,1);
-	}
-}
-
-
 cur_frm.fields_dict['transporter_name'].get_query = function(doc) {
 	return 'SELECT DISTINCT `tabSupplier`.`name` FROM `tabSupplier` WHERE `tabSupplier`.supplier_type = "transporter" AND `tabSupplier`.docstatus != 2 AND `tabSupplier`.%(key)s LIKE "%s" ORDER BY `tabSupplier`.`name` LIMIT 50';
 }
diff --git a/stock/doctype/delivery_note/delivery_note.py b/stock/doctype/delivery_note/delivery_note.py
index 363fb39..950d687 100644
--- a/stock/doctype/delivery_note/delivery_note.py
+++ b/stock/doctype/delivery_note/delivery_note.py
@@ -34,6 +34,9 @@
 		self.doclist = doclist
 		self.tname = 'Delivery Note Item'
 		self.fname = 'delivery_note_details'
+		
+	def set_customer_defaults(self):
+		self.get_default_customer_shipping_address()
 
 	def validate_fiscal_year(self):
 		get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,self.doc.posting_date,'Posting Date')
@@ -78,25 +81,6 @@
 	def get_tc_details(self):
 		return get_obj('Sales Common').get_tc_details(self)
 
-	def get_item_details(self, args=None):
-		import json
-		args = args and json.loads(args) or {}
-		if args.get('item_code'):
-			return get_obj('Sales Common').get_item_details(args, self)
-		else:
-			obj = get_obj('Sales Common')
-			for doc in self.doclist:
-				if doc.fields.get('item_code'):
-					arg = {
-						'item_code':doc.fields.get('item_code'),
-						'expense_account':doc.fields.get('expense_account'), 
-						'cost_center': doc.fields.get('cost_center'), 
-						'warehouse': doc.fields.get('warehouse')};
-					ret = obj.get_item_defaults(arg)
-					for r in ret:
-						if not doc.fields.get(r):
-							doc.fields[r] = ret[r]					
-
 	def get_barcode_details(self, barcode):
 		return get_obj('Sales Common').get_barcode_details(barcode)
 
@@ -105,12 +89,6 @@
 		"""Re-calculates Basic Rate & amount based on Price List Selected"""
 		get_obj('Sales Common').get_adj_percent(self)
 
-
-	def get_actual_qty(self,args):
-		"""Get Actual Qty of item in warehouse selected"""
-		return get_obj('Sales Common').get_available_qty(eval(args))
-
-
 	def get_rate(self,arg):
 		return get_obj('Sales Common').get_rate(arg)
 
diff --git a/stock/doctype/material_request/material_request.js b/stock/doctype/material_request/material_request.js
index 3d4eed4..881a764 100644
--- a/stock/doctype/material_request/material_request.js
+++ b/stock/doctype/material_request/material_request.js
@@ -55,22 +55,7 @@
 
 // for backward compatibility: combine new and previous states
 $.extend(cur_frm.cscript, new_cscript);
-
 	
-cur_frm.cscript.onload_post_render = function(doc, cdt, cdn) {
-	// second call
-	if(doc.__islocal){ 
-		cur_frm.cscript.get_item_defaults(doc);
-	}	
-};
-
-cur_frm.cscript.get_item_defaults = function(doc) {
-		var ch = getchildren( 'Material Request Item', doc.name, 'indent_details');
-		if (flt(ch.length) > 0){
-			$c_obj(make_doclist(doc.doctype, doc.name), 'get_item_defaults', '', function(r, rt) {refresh_field('indent_details'); });
-		}
-};
-
 cur_frm.cscript.qty = function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];
 	if (flt(d.qty) < flt(d.min_order_qty))
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.js b/stock/doctype/purchase_receipt/purchase_receipt.js
index 20740e7..f405a55 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.js
+++ b/stock/doctype/purchase_receipt/purchase_receipt.js
@@ -19,10 +19,11 @@
 cur_frm.cscript.other_fname = "purchase_tax_details";
 
 wn.require('app/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.js');
-wn.require('app/buying/doctype/purchase_common/purchase_common.js');
 wn.require('app/utilities/doctype/sms_control/sms_control.js');
+wn.require('app/buying/doctype/purchase_common/purchase_common.js');
 
-erpnext.buying.PurchaseReceiptController = erpnext.buying.BuyingController.extend({
+wn.provide("erpnext.stock");
+erpnext.stock.PurchaseReceiptController = erpnext.buying.BuyingController.extend({
 	refresh: function() {
 		this._super();
 		
@@ -37,29 +38,49 @@
 		if(wn.boot.control_panel.country == 'India') {
 			unhide_field(['challan_no', 'challan_date']);
 		}
-	}, 
+	},
+	
+	received_qty: function(doc, cdt, cdn) {
+		var item = wn.model.get_doc(cdt, cdn);
+		wn.model.round_floats_in(item, ["qty", "received_qty"]);
+
+		item.qty = (item.qty < item.received_qty) ? item.qty : item.received_qty;
+		this.qty(doc, cdt, cdn);
+	},
+	
+	qty: function(doc, cdt, cdn) {
+		var item = wn.model.get_doc(cdt, cdn);
+		wn.model.round_floats_in(item, ["qty", "received_qty"]);
+		
+		if(item.qty > item.received_qty) {
+			msgprint(wn._("Error") + ": " + wn._(wn.meta.get_label(item.doctype, "qty", item.name))
+				+ " > " + wn._(wn.meta.get_label(item.doctype, "received_qty", item.name)));
+			item.qty = item.rejected_qty = 0.0;
+		} else {
+			item.rejected_qty = flt(item.received_qty - item.qty, precision("rejected_qty", item));
+		}
+		
+		this._super();
+	},
+	
+	rejected_qty: function(doc, cdt, cdn) {
+		var item = wn.model.get_doc(cdt, cdn);
+		wn.model.round_floats_in(item, ["received_qty", "rejected_qty"]);
+		
+		if(item.rejected_qty > item.received_qty) {
+			msgprint(wn._("Error") + ": " + wn._(wn.meta.get_label(item.doctype, "rejected_qty", item.name))
+				+ " > " + wn._(wn.meta.get_label(item.doctype, "received_qty", item.name)));
+			item.qty = item.rejected_qty = 0.0;
+		} else {
+			item.qty = flt(item.received_qty - item.rejected_qty, precision("qty", item));
+		}
+		
+		this.qty(doc, cdt, cdn);
+	},
 });
 
-var new_cscript = new erpnext.buying.PurchaseReceiptController({frm: cur_frm});
-
 // for backward compatibility: combine new and previous states
-$.extend(cur_frm.cscript, new_cscript);
-
-cur_frm.cscript.onload = function(doc, cdt, cdn) {
-	if(!doc.fiscal_year && doc.__islocal){ wn.model.set_default_values(doc);}
-	if (!doc.posting_date) doc.posting_date = dateutil.obj_to_str(new Date());
-	if (!doc.transaction_date) doc.transaction_date = dateutil.obj_to_str(new Date());
-	if (!doc.status) doc.status = 'Draft';
-}
-
-cur_frm.cscript.supplier = function(doc,dt,dn) {
-	if (doc.supplier) {
-		get_server_fields('get_default_supplier_address',
-			JSON.stringify({ supplier: doc.supplier }),'', doc, dt, dn, 1, function() {
-				cur_frm.refresh();
-			});
-	}
-}
+$.extend(cur_frm.cscript, new erpnext.stock.PurchaseReceiptController({frm: cur_frm}));
 
 cur_frm.cscript.supplier_address = cur_frm.cscript.contact_person = function(doc,dt,dn) {		
 	if(doc.supplier) get_server_fields('get_supplier_address', JSON.stringify({supplier: doc.supplier, address: doc.supplier_address, contact: doc.contact_person}),'', doc, dt, dn, 1);
@@ -137,81 +158,6 @@
 	return 'SELECT `tabPrint Heading`.name FROM `tabPrint Heading` WHERE `tabPrint Heading`.docstatus !=2 AND `tabPrint Heading`.name LIKE "%s" ORDER BY `tabPrint Heading`.name ASC LIMIT 50';
 }
 
-//========================= Received Qty =============================================================
-
-cur_frm.cscript.received_qty = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	ret = {
-			'qty' : (flt(d.qty) && flt(d.qty) < flt(d.received_qty)) 
-			 	? flt(d.qty) : flt(d.received_qty),
-			'stock_qty': 0,
-			'rejected_qty' : 0,
-		}
-	set_multiple('Purchase Receipt Item', cdn, ret, 'purchase_receipt_details');
-	cur_frm.cscript.calc_amount(doc, 2);
-}
-
-//======================== Qty (Accepted Qty) =========================================================
-
-cur_frm.cscript.qty = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	// Step 1 :=> Check If Qty > Received Qty
-	if (flt(d.qty) > flt(d.received_qty)) {
-		alert("Accepted Qty cannot be greater than Received Qty")
-		ret = {
-			'qty' : 0,
-			'stock_qty': 0,
-			'rejected_qty' : 0
-		}
-		// => Set Qty = 0 and rejected_qty = 0
-		set_multiple('Purchase Receipt Item', cdn, ret, 'purchase_receipt_details');
-		cur_frm.cscript.calc_amount(doc, 2);
-		// => Return
-		return
-	}
-	// Step 2 :=> Check IF Qty <= REceived Qty
-	else {
-		ret = {
-			'rejected_qty':flt(d.received_qty) - flt(d.qty)
-		}
-		// => Set Rejected Qty = Received Qty - Qty
-		set_multiple('Purchase Receipt Item', cdn, ret, 'purchase_receipt_details');
-		// => Calculate Amount
-		cur_frm.cscript.calc_amount(doc, 2);
-		cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
-	}	
-}
-
-//======================== Rejected Qty =========================================================
-cur_frm.cscript.rejected_qty = function(doc, cdt, cdn) {
-	var d = locals[cdt][cdn];
-	// Step 1 :=> Check If Rejected Qty > Received Qty
-	if (flt(d.rejected_qty) > flt(d.received_qty)) {
-		alert("Rejected Qty cannot be greater than Received Qty") 
-		ret = {
-			'qty' : 0,
-			'stock_qty': 0,
-			'rejected_qty' : 0
-		}
-		// => Set Qty = 0 and rejected_qty = 0
-		set_multiple('Purchase Receipt Item', cdn, ret, 'purchase_receipt_details');
-		cur_frm.cscript.calc_amount(doc, 2);
-		// => Return
-		return
-	}
-	// Step 2 :=> Check IF Rejected Qty <= REceived Qty
-	else {
-		ret = {
-			'qty':flt(d.received_qty) - flt(d.rejected_qty)
-		}
-		// => Set Qty = Received Qty - Rejected Qty
-		set_multiple('Purchase Receipt Item', cdn, ret, 'purchase_receipt_details');
-		// Calculate Amount
-		cur_frm.cscript.calc_amount(doc, 2);
-		cur_frm.cscript.update_stock_qty(doc,cdt,cdn);
-	}
-}
-
 //================================= Purchase Order No Get Query ====================================
 cur_frm.fields_dict['purchase_order_no'].get_query = function(doc) {
 	if (doc.supplier)
diff --git a/utilities/transaction_base.py b/utilities/transaction_base.py
index d4c61f5..f1a06c9 100644
--- a/utilities/transaction_base.py
+++ b/utilities/transaction_base.py
@@ -298,16 +298,27 @@
 		msgprint(_("Please specify Company"), raise_exception=True)
 	
 def validate_currency(args, item, meta=None):
+	from webnotes.model.meta import get_field_precision
 	if not meta:
 		meta = webnotes.get_doctype(args.doctype)
-	
+		
 	# validate conversion rate
 	if meta.get_field("currency"):
 		validate_conversion_rate(args.currency, args.conversion_rate, 
 			meta.get_label("conversion_rate"), args.company)
+		
+		# round it
+		args.conversion_rate = flt(args.conversion_rate, 
+			get_field_precision(meta.get_field("conversion_rate"), args))
 	
 	# validate price list conversion rate
 	if meta.get_field("price_list_currency") and args.price_list_name and \
 		args.price_list_currency:
 		validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate, 
-			meta.get_label("plc_conversion_rate"), args.company)
\ No newline at end of file
+			meta.get_label("plc_conversion_rate"), args.company)
+		
+		# round it
+		args.plc_conversion_rate = flt(args.plc_conversion_rate, 
+			get_field_precision(meta.get_field("plc_conversion_rate"), args))	
+	
+	
\ No newline at end of file