Merge branch 'master' into edge
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.py b/accounts/doctype/purchase_invoice/purchase_invoice.py
index f535d56..fb9977c 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -33,6 +33,47 @@
 		self.doc, self.doclist = d, dl 
 		self.tname = 'Purchase Invoice Item'
 		self.fname = 'entries'
+		
+	def validate(self):
+		super(DocType, self).validate()
+		
+		self.po_required()
+		self.pr_required()
+		self.check_active_purchase_items()
+		self.check_conversion_rate()
+		self.validate_bill_no_date()
+		self.validate_bill_no()
+		self.validate_reference_value()
+		self.validate_credit_acc()
+		self.clear_unallocated_advances("Purchase Invoice Advance", "advance_allocation_details")
+		self.check_for_acc_head_of_supplier()
+		self.check_for_stopped_status()
+
+		self.po_list, self.pr_list = [], []
+		for d in getlist(self.doclist, 'entries'):
+			self.validate_supplier(d)
+			self.validate_po_pr(d)
+			if not d.purchase_order in self.po_list:
+				self.po_list.append(d.purchase_order)
+			if not d.purhcase_receipt in self.pr_list:
+				self.pr_list.append(d.purchase_receipt)
+
+
+		if not self.doc.is_opening:
+			self.doc.is_opening = 'No'
+
+		self.set_aging_date()
+
+		#set against account for credit to
+		self.set_against_expense_account()
+
+		#FY validation
+		get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,
+		 	self.doc.posting_date,'Posting Date')
+		
+		self.validate_write_off_account()
+		self.update_raw_material_cost()
+		self.update_valuation_rate("entries")
 
 	def get_credit_to(self):
 		acc_head = sql("select name, credit_days from `tabAccount` where (name = %s or (master_name = %s and master_type = 'supplier')) and docstatus != 2", (cstr(self.doc.supplier) + " - " + self.company_abbr,self.doc.supplier))		
@@ -265,7 +306,7 @@
 	def set_against_expense_account(self):
 		auto_inventory_accounting = \
 			cint(webnotes.defaults.get_global_default("auto_inventory_accounting"))
-		stock_not_billed_account = "Stock Received But Not Billed - %s" % self.company_abbr
+		stock_not_billed_account = self.get_company_default("stock_received_but_not_billed")
 		
 		against_accounts = []
 		for item in self.doclist.get({"parentfield": "entries"}):
@@ -277,6 +318,10 @@
 				if stock_not_billed_account not in against_accounts:
 					against_accounts.append(stock_not_billed_account)
 			
+			elif not item.expense_head:
+				msgprint(_("""Expense account is mandatory for item: """) + item.item_code, 
+					raise_exception=1)
+			
 			elif item.expense_head not in against_accounts:
 				# if no auto_inventory_accounting or not a stock item
 				against_accounts.append(item.expense_head)
@@ -303,47 +348,6 @@
 		if self.doc.write_off_amount and not self.doc.write_off_account:
 			msgprint("Please enter Write Off Account", raise_exception=1)
 
-	def validate(self):
-		super(DocType, self).validate()
-		
-		self.po_required()
-		self.pr_required()
-		self.check_active_purchase_items()
-		self.check_conversion_rate()
-		self.validate_bill_no_date()
-		self.validate_bill_no()
-		self.validate_reference_value()
-		self.validate_credit_acc()
-		self.clear_unallocated_advances("Purchase Invoice Advance", "advance_allocation_details")
-		self.check_for_acc_head_of_supplier()
-		self.check_for_stopped_status()
-
-		self.po_list, self.pr_list = [], []
-		for d in getlist(self.doclist, 'entries'):
-			self.validate_supplier(d)
-			self.validate_po_pr(d)
-			if not d.purchase_order in self.po_list:
-				self.po_list.append(d.purchase_order)
-			if not d.purhcase_receipt in self.pr_list:
-				self.pr_list.append(d.purchase_receipt)
-
-
-		if not self.doc.is_opening:
-			self.doc.is_opening = 'No'
-
-		self.set_aging_date()
-
-		#set against account for credit to
-		self.set_against_expense_account()
-
-		#FY validation
-		get_obj('Sales Common').validate_fiscal_year(self.doc.fiscal_year,
-		 	self.doc.posting_date,'Posting Date')
-		
-		self.validate_write_off_account()
-		self.update_raw_material_cost()
-		self.update_valuation_rate("entries")
-
 	def check_prev_docstatus(self):
 		for d in getlist(self.doclist,'entries'):
 			if d.purchase_order:
@@ -445,7 +449,7 @@
 		# item gl entries
 		stock_item_and_auto_inventory_accounting = False
 		if auto_inventory_accounting:
-			stock_acocunt = self.get_default_account("stock_received_but_not_billed")
+			stock_account = self.get_company_default("stock_received_but_not_billed")
 			
 		for item in self.doclist.get({"parentfield": "entries"}):
 			if auto_inventory_accounting and item.item_code in self.stock_items:
@@ -458,7 +462,7 @@
 					
 					gl_entries.append(
 						self.get_gl_dict({
-							"account": stock_acocunt,
+							"account": stock_account,
 							"against": self.doc.credit_to,
 							"debit": flt(item.valuation_rate) * flt(item.conversion_factor) \
 								*  flt(item.qty),
@@ -483,8 +487,8 @@
 			# this will balance out valuation amount included in cost of goods sold
 			gl_entries.append(
 				self.get_gl_dict({
-					"account": self.get_default_account("expenses_included_in_valuation"),
-					"cost_center": "Auto Inventory Accounting - %s" % self.company_abbr,
+					"account": self.get_company_default("expenses_included_in_valuation"),
+					"cost_center": self.get_company_default("stock_adjustment_cost_center"),
 					"against": self.doc.credit_to,
 					"credit": valuation_tax,
 					"remarks": self.doc.remarks or "Accounting Entry for Stock"
@@ -525,8 +529,8 @@
 					and is_active = 1 """, (d.item_code,))
 				rm_cost = rm_cost and flt(rm_cost[0][0]) or 0
 				
-				d.conversion_factor = d.conversion_factor or webnotes.conn.get_value(
+				d.conversion_factor = d.conversion_factor or flt(webnotes.conn.get_value(
 					"UOM Conversion Detail", {"parent": d.item_code, "uom": d.uom}, 
-					"conversion_factor") or 1
+					"conversion_factor")) or 1
 		
 				d.rm_supp_cost = rm_cost * flt(d.qty) * flt(d.conversion_factor)
\ No newline at end of file
diff --git a/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index 6d9cfca..621604b 100644
--- a/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -109,12 +109,49 @@
 			# print tax.account_head, tax.tax_amount, tax.item_wise_tax_detail
 
 		expected_values = [
-			["_Test Item Home Desktop 100", 90],
-			["_Test Item Home Desktop 200", 135]
+			["_Test Item Home Desktop 100", 90, 59],
+			["_Test Item Home Desktop 200", 135, 177]
 		]
 		for i, item in enumerate(wrapper.doclist.get({"parentfield": "entries"})):
 			self.assertEqual(item.item_code, expected_values[i][0])
 			self.assertEqual(item.item_tax_amount, expected_values[i][1])
+			self.assertEqual(item.valuation_rate, expected_values[i][2])
+			
+	def test_purchase_invoice_with_subcontracted_item(self):
+		wrapper = webnotes.bean(copy=test_records[0])
+		wrapper.doclist[1].item_code = "_Test FG Item"
+		wrapper.run_method("calculate_taxes_and_totals")
+		wrapper.insert()
+		wrapper.load_from_db()
+
+		self.assertEqual(wrapper.doclist[0].net_total, 1250)
+
+		# tax amounts
+		expected_values = [
+			["_Test Account Shipping Charges - _TC", 100, 1350],
+			["_Test Account Customs Duty - _TC", 125, 1350],
+			["_Test Account Excise Duty - _TC", 140, 1490],
+			["_Test Account Education Cess - _TC", 2.8, 1492.8],
+			["_Test Account S&H Education Cess - _TC", 1.4, 1494.2],
+			["_Test Account CST - _TC", 29.88, 1524.08],
+			["_Test Account VAT - _TC", 156.25, 1680.33],
+			["_Test Account Discount - _TC", 168.03, 1512.30],
+		]
+
+		for i, tax in enumerate(wrapper.doclist.get({"parentfield": "purchase_tax_details"})):
+			self.assertEqual(tax.account_head, expected_values[i][0])
+			self.assertEqual(tax.tax_amount, expected_values[i][1])
+			self.assertEqual(tax.total, expected_values[i][2])
+			# print tax.account_head, tax.tax_amount, tax.item_wise_tax_detail
+
+		expected_values = [
+			["_Test FG Item", 90, 7059],
+			["_Test Item Home Desktop 200", 135, 177]
+		]
+		for i, item in enumerate(wrapper.doclist.get({"parentfield": "entries"})):
+			self.assertEqual(item.item_code, expected_values[i][0])
+			self.assertEqual(item.item_tax_amount, expected_values[i][1])
+			self.assertEqual(item.valuation_rate, expected_values[i][2])
 			
 	def test_purchase_invoice_with_advance(self):
 		from accounts.doctype.journal_voucher.test_journal_voucher \
diff --git a/accounts/doctype/sales_invoice/sales_invoice.py b/accounts/doctype/sales_invoice/sales_invoice.py
index 9b5c80c..4b0f3b1 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/accounts/doctype/sales_invoice/sales_invoice.py
@@ -249,7 +249,7 @@
 					['Delivery Note Item', 'Sales Invoice Item'],
 					['Sales Taxes and Charges','Sales Taxes and Charges'],
 					['Sales Team','Sales Team']]""")								
-			self.get_income_account('entries')
+			self.get_income_expense_account('entries')
 			
 		elif self.doc.sales_order_main:
 			self.validate_prev_docname('sales order')
@@ -259,7 +259,7 @@
 				"""[['Sales Order', 'Sales Invoice'],['Sales Order Item', 'Sales Invoice Item'], 
 				['Sales Taxes and Charges','Sales Taxes and Charges'], 
 				['Sales Team', 'Sales Team']]""")
-			self.get_income_account('entries')
+			self.get_income_expense_account('entries')
 			
 		ret = self.get_debit_to()
 		self.doc.debit_to = ret.get('debit_to')
@@ -269,16 +269,21 @@
 		"""
 			Loads default accounts from items, customer when called from mapper
 		"""
-		self.get_income_account('entries')
+		self.get_income_expense_account('entries')
 		
 		
-	def get_income_account(self,doctype):		
+	def get_income_expense_account(self,doctype):		
 		for d in getlist(self.doclist, doctype):			
 			if d.item_code:
-				item = webnotes.conn.get_value("Item", d.item_code, 
-					["default_income_account", "default_sales_cost_center"], as_dict=True)
+				item = webnotes.conn.get_value("Item", d.item_code, ["default_income_account", 
+					"default_sales_cost_center", "purchase_account", "cost_center"], as_dict=True)
 				d.income_account = item['default_income_account'] or ""
-				d.cost_center = item['default_sales_cost_center'] or ""			
+				d.cost_center = item['default_sales_cost_center'] or ""
+				
+				if cint(webnotes.defaults.get_global_default("auto_inventory_accounting")) \
+						and cint(self.doc.is_pos) and cint(self.doc.update_stock):
+					d.expense_account = item['purchase_account'] or ""
+					d.purchase_cost_center = item['cost_center'] or ""
 
 
 	def get_item_details(self, args=None):
@@ -294,8 +299,10 @@
 						'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')
-					};
+						'warehouse': doc.fields.get('warehouse'),
+						'expense_account': doc.fields.get('expense_account'),
+						'purchase_cost_center': doc.fields.get('purchase_cost_center')
+					}
 
 					ret = self.get_pos_details(arg)
 					for r in ret:
diff --git a/accounts/doctype/sales_invoice_item/sales_invoice_item.txt b/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
index bc51198..221359c 100644
--- a/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
+++ b/accounts/doctype/sales_invoice_item/sales_invoice_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-03-07 11:42:55", 
   "docstatus": 0, 
-  "modified": "2013-03-21 18:35:47", 
+  "modified": "2013-03-22 18:40:48", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -222,7 +222,7 @@
   "fieldname": "cost_center", 
   "fieldtype": "Link", 
   "in_filter": 1, 
-  "label": "Cost Center", 
+  "label": "Sales Cost Center", 
   "oldfieldname": "cost_center", 
   "oldfieldtype": "Link", 
   "options": "Cost Center", 
@@ -234,6 +234,17 @@
  }, 
  {
   "doctype": "DocField", 
+  "fieldname": "purchase_cost_center", 
+  "fieldtype": "Link", 
+  "hidden": 1, 
+  "in_filter": 1, 
+  "label": "Purchase Cost Center", 
+  "options": "Cost Center", 
+  "print_hide": 1, 
+  "width": "120px"
+ }, 
+ {
+  "doctype": "DocField", 
   "fieldname": "serial_no", 
   "fieldtype": "Small Text", 
   "in_filter": 1, 
diff --git a/accounts/utils.py b/accounts/utils.py
index 051cdd1..92173ab 100644
--- a/accounts/utils.py
+++ b/accounts/utils.py
@@ -248,3 +248,64 @@
 		and voucher_no != ifnull(against_voucher, "")
 		and ifnull(is_cancelled, "No")="No" """,
 		(now(), webnotes.session.user, ref_type, ref_no))
+
+@webnotes.whitelist()
+def get_company_default(company, fieldname):
+	value = webnotes.conn.get_value("Company", company, fieldname)
+	
+	if not value:
+		msgprint(_("Please mention default value for '") + 
+			_(webnotes.get_doctype("company").get_label(fieldname) + 
+			_("' in Company: ") + company), raise_exception=True)
+			
+	return value
+		
+def create_stock_in_hand_jv(reverse=False):
+	from webnotes.utils import nowdate
+	today = nowdate()
+	fiscal_year = get_fiscal_year(today)[0]
+	
+	for company in webnotes.conn.sql_list("select name from `tabCompany`"):
+		stock_rbnb_value = get_stock_rbnb_value(company)
+		
+		jv = webnotes.bean([
+			{
+				"doctype": "Journal Voucher",
+				"naming_series": "_PATCH-",
+				"company": company,
+				"posting_date": today,
+				"fiscal_year": fiscal_year,
+				"voucher_type": "Journal Entry"
+			},
+			{
+				"doctype": "Journal Voucher Detail",
+				"parentfield": "entries",
+				"account": get_company_default(company, "stock_received_but_not_billed"),
+				(reverse and "debit" or "credit"): stock_rbnb_value
+			},
+			{
+				"doctype": "Journal Voucher Detail",
+				"parentfield": "entries",
+				"account": get_company_default(company, "stock_adjustment_account"),
+				(reverse and "credit" or "debit"): stock_rbnb_value
+			},
+		])
+		jv.insert()
+		jv.submit()
+		
+def get_stock_rbnb_value(company):	
+	total_received_amount = webnotes.conn.sql("""select sum(valuation_amount) 
+		from `tabPurchase Receipt Item` pr_item where docstatus=1 
+		and exists(select name from `tabItem` where name = pr_item.item_code 
+			and is_stock_item='Yes')
+		and exist(select name from `tabPurchase Receipt` 
+			where name = pr_item.parent and company = %s)""", company)
+		
+	total_billed_amount = webnotes.conn.sql("""select sum(valuation_amount) 
+		from `tabPurchase Invoice Item` pi_item where docstatus=1 
+		and exists(select name from `tabItem` where name = pi_item.item_code 
+			and is_stock_item='Yes')
+		and exist(select name from `tabPurchase Invoice` 
+			where name = pi_item.parent and company = %s)""", company)
+		
+	return flt(total_received_amount[0][0]) - flt(total_billed_amount[0][0])
diff --git a/buying/doctype/purchase_common/purchase_common.py b/buying/doctype/purchase_common/purchase_common.py
index 6af08c6..d5b563b 100644
--- a/buying/doctype/purchase_common/purchase_common.py
+++ b/buying/doctype/purchase_common/purchase_common.py
@@ -402,7 +402,7 @@
 		yed=add_days(str(ysd),365)		
 		if str(transaction_date) < str(ysd) or str(transaction_date) > str(yed):
 			msgprint("'%s' Not Within The Fiscal Year"%(dn))
-			raise Exception			
+			raise Exception
 
 	def load_default_taxes(self, obj):
 		return self.get_purchase_tax_details(obj, 1)
diff --git a/controllers/accounts_controller.py b/controllers/accounts_controller.py
index ac6481c..0e7c108 100644
--- a/controllers/accounts_controller.py
+++ b/controllers/accounts_controller.py
@@ -76,14 +76,9 @@
 				"allocate_amount": 0
 			})
 		
-	def get_default_account(self, account_for):
-		account = webnotes.conn.get_value("Company", self.doc.company, account_for)
-		if not account:
-			msgprint(_("Please mention default account for '") + 
-				_(webnotes.get_doctype("company").get_label(account_for) + 
-				_("' in Company: ") + self.doc.company), raise_exception=True)
-				
-		return account
+	def get_company_default(self, fieldname):
+		from accounts.utils import get_company_default
+		return get_company_default(self.doc.company, fieldname)
 		
 	@property
 	def stock_items(self):
@@ -101,8 +96,3 @@
 			self._abbr = webnotes.conn.get_value("Company", self.doc.company, "abbr")
 			
 		return self._abbr
-
-
-@webnotes.whitelist()
-def get_default_account(account_for, company):
-	return webnotes.conn.get_value("Company", company, account_for)
diff --git a/controllers/buying_controller.py b/controllers/buying_controller.py
index 2c2bb44..560dec2 100644
--- a/controllers/buying_controller.py
+++ b/controllers/buying_controller.py
@@ -332,9 +332,9 @@
 	# update valuation rate
 	def update_valuation_rate(self, parentfield):
 		for d in self.doclist.get({"parentfield": parentfield}):
-			d.conversion_factor = d.conversion_factor or webnotes.conn.get_value(
+			d.conversion_factor = d.conversion_factor or flt(webnotes.conn.get_value(
 				"UOM Conversion Detail", {"parent": d.item_code, "uom": d.uom}, 
-				"conversion_factor") or 1
+				"conversion_factor")) or 1
 			if d.item_code and d.qty:
 				# if no item code, which is sometimes the case in purchase invoice, 
 				# then it is not possible to track valuation against it
diff --git a/controllers/selling_controller.py b/controllers/selling_controller.py
index 538c5c1..ab002be 100644
--- a/controllers/selling_controller.py
+++ b/controllers/selling_controller.py
@@ -18,6 +18,7 @@
 import webnotes
 from webnotes.utils import cint
 from setup.utils import get_company_currency
+from webnotes import msgprint, _
 
 from controllers.stock_controller import StockController
 
@@ -58,5 +59,10 @@
 						self.doc.doctype, self.doc.name, item.name, stock_ledger_entries, 
 						item_sales_bom)
 					item.buying_amount = buying_amount > 0 and buying_amount or 0
-					webnotes.conn.set_value(self.tname, item.name, "buying_amount", 
-						item.buying_amount)
\ No newline at end of file
+					webnotes.conn.set_value(item.doctype, item.name, "buying_amount", 
+						item.buying_amount)
+						
+	def check_expense_account(self, item):
+		if item.buying_amount and not item.expense_account:
+			msgprint(_("""Expense account is mandatory for item: """) + item.item_code, 
+				raise_exception=1)	
\ No newline at end of file
diff --git a/controllers/stock_controller.py b/controllers/stock_controller.py
index c76865d..89f62aa 100644
--- a/controllers/stock_controller.py
+++ b/controllers/stock_controller.py
@@ -23,7 +23,9 @@
 	def get_gl_entries_for_stock(self, against_stock_account, amount, 
 			stock_in_hand_account=None, cost_center=None):
 		if not stock_in_hand_account:
-			stock_in_hand_account = self.get_default_account("stock_in_hand_account")
+			stock_in_hand_account = self.get_company_default("stock_in_hand_account")
+		if not cost_center:
+			cost_center = self.get_company_default("stock_adjustment_cost_center")
 		
 		if amount:
 			gl_entries = [
@@ -46,12 +48,6 @@
 			]
 			
 			return gl_entries
-			
-			
-	def check_expense_account(self, item):
-		if not item.expense_account:
-			msgprint(_("""Expense account is mandatory for item: """) + item.item_code, 
-				raise_exception=1)	
 		
 	def get_stock_ledger_entries(self, item_list=None, warehouse_list=None):
 		if not (item_list and warehouse_list):
diff --git a/patches/march_2013/p07_update_valuation_rate.py b/patches/march_2013/p07_update_valuation_rate.py
new file mode 100644
index 0000000..0bce8a4
--- /dev/null
+++ b/patches/march_2013/p07_update_valuation_rate.py
@@ -0,0 +1,13 @@
+import webnotes
+
+def execute():
+	for purchase_invoice in webnotes.conn.sql("""select distinct parent 
+		from `tabPurchase Invoice Item` where docstatus = 1 and ifnull(valuation_rate, 0)=0"""):
+		pi = webnotes.get_obj("Purchase Invoice", purchase_invoice)
+		pi.calculate_taxes_and_totals()
+		pi.update_raw_material_cost()
+		pi.update_valuation_rate("entries")
+		for item in pi.doclist.get({"parentfield": "entries"}):
+			webnotes.conn.set_value("Purchase Invoice Item", item.name, "valuation_rate",
+				item.valuation_rate)
+	
\ No newline at end of file
diff --git a/selling/doctype/sales_common/sales_common.py b/selling/doctype/sales_common/sales_common.py
index 12ae4a8..fca96b8 100644
--- a/selling/doctype/sales_common/sales_common.py
+++ b/selling/doctype/sales_common/sales_common.py
@@ -17,11 +17,11 @@
 from __future__ import unicode_literals
 import webnotes
 
-from webnotes.utils import cint, cstr, flt, getdate, nowdate, formatdate
+from webnotes.utils import cint, cstr, flt, getdate, nowdate
 from webnotes.model.doc import addchild
 from webnotes.model.bean import getlist
 from webnotes.model.code import get_obj
-from webnotes import msgprint, _
+from webnotes import msgprint
 from setup.utils import get_company_currency
 
 get_value = webnotes.conn.get_value
@@ -127,7 +127,7 @@
 		if not obj.doc.price_list_name:
 			msgprint("Please Select Price List before selecting Items")
 			raise Exception
-		item = webnotes.conn.sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, 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)
+		item = webnotes.conn.sql("select description, item_name, brand, item_group, stock_uom, default_warehouse, default_income_account, default_sales_cost_center, purchase_account, cost_center, 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])
@@ -141,7 +141,9 @@
 			'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'),
+			'purchase_cost_center'	: item and item[0]['cost_center'] or args.get('purchase_cost_center'),
 			'qty'					: 1.00,	 # this is done coz if item once fetched is fetched again thn its qty shld be reset to 1
 			'adj_rate'				: 0,
 			'amount'				: 0,
diff --git a/setup/doctype/backup_manager/backup_dropbox.py b/setup/doctype/backup_manager/backup_dropbox.py
index 4e9efdf..2901638 100644
--- a/setup/doctype/backup_manager/backup_dropbox.py
+++ b/setup/doctype/backup_manager/backup_dropbox.py
@@ -44,7 +44,10 @@
 			webnotes.conn.set_value("Backup Manager", "Backup Manager", "dropbox_access_secret", access_token.secret)
 			webnotes.conn.set_value("Backup Manager", "Backup Manager", "dropbox_access_allowed", allowed)
 			dropbox_client = client.DropboxClient(sess)
-			dropbox_client.file_create_folder("files")
+			try:
+				dropbox_client.file_create_folder("files")
+			except:
+				pass
 
 		else:
 			allowed = 0
@@ -94,7 +97,11 @@
 			upload_file_to_dropbox(filepath, "files", dropbox_client)
 
 def get_dropbox_session():
-	from dropbox import session
+	try:
+		from dropbox import session
+	except:
+		webnotes.msgprint(_("Please install dropbox python module"), raise_exception=1)
+		
 	try:
 		from conf import dropbox_access_key, dropbox_secret_key
 	except ImportError:
@@ -107,16 +114,20 @@
 	from dropbox import rest
 	size = os.stat(filename).st_size
 	f = open(filename,'r')
-	if size > 4194304:
+	
+	# if max packet size reached, use chunked uploader
+	max_packet_size = 4194304
+	
+	if size > max_packet_size:
 		uploader = dropbox_client.get_chunked_uploader(f, size)
 		while uploader.offset < size:
 			try:
 				uploader.upload_chunked()
-				uploader.finish(os.path.join(folder, os.path.basename(filename)), overwrite=True)
+				uploader.finish(folder + "/" + os.path.basename(filename), overwrite=True)
 			except rest.ErrorResponse:
 				pass
 	else:
-		dropbox_client.put_file(os.path.join(folder, os.path.basename(filename)), f, overwrite=True)
+		dropbox_client.put_file(folder + "/" + os.path.basename(filename), f, overwrite=True)
 
 if __name__=="__main__":
 	backup_to_dropbox()
\ No newline at end of file
diff --git a/setup/doctype/company/company.js b/setup/doctype/company/company.js
index a898823..735f514 100644
--- a/setup/doctype/company/company.js
+++ b/setup/doctype/company/company.js
@@ -97,4 +97,11 @@
 			"company": doc.name
 		}
 	}
+}
+
+cur_frm.fields_dict["stock_adjustment_cost_center"].get_query = function(doc) {
+	return {
+		"query": "accounts.utils.get_cost_center_list", 
+		"filters": {"company": doc.name}
+	}
 }
\ No newline at end of file
diff --git a/setup/doctype/company/company.py b/setup/doctype/company/company.py
index 15241a2..a2e56eb 100644
--- a/setup/doctype/company/company.py
+++ b/setup/doctype/company/company.py
@@ -199,12 +199,7 @@
 		if not self.doc.payables_group and webnotes.conn.exists('Account', 
 			'Accounts Payable - ' + self.doc.abbr):
 				webnotes.conn.set(self.doc, 'payables_group', 'Accounts Payable - ' + self.doc.abbr)
-			
-		if not self.doc.stock_delivered_but_not_billed and webnotes.conn.exists("Account", 
-			"Stock Delivered But Not Billed - " + self.doc.abbr):
-				webnotes.conn.set(self.doc, "stock_delivered_but_not_billed", 
-					"Stock Delivered But Not Billed - " + self.doc.abbr)
-					
+								
 		if not self.doc.stock_received_but_not_billed and webnotes.conn.exists("Account", 
 			"Stock Received But Not Billed - " + self.doc.abbr):
 				webnotes.conn.set(self.doc, "stock_received_but_not_billed", 
@@ -219,7 +214,12 @@
 			"Expenses Included In Valuation - " + self.doc.abbr):
 				webnotes.conn.set(self.doc, "expenses_included_in_valuation", 
 					"Expenses Included In Valuation - " + self.doc.abbr)
-			
+		
+		if not self.doc.stock_adjustment_cost_center and webnotes.conn.exists("Cost Center", 
+			"Auto Inventory Accounting - " + self.doc.abbr):
+				webnotes.conn.set(self.doc, "stock_adjustment_cost_center", 
+					"Auto Inventory Accounting - " + self.doc.abbr)
+	
 	# Create default cost center
 	# ---------------------------------------------------
 	def create_default_cost_center(self):
diff --git a/setup/doctype/company/company.txt b/setup/doctype/company/company.txt
index 4d2dcda..e9976aa 100644
--- a/setup/doctype/company/company.txt
+++ b/setup/doctype/company/company.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-02-27 09:38:05", 
   "docstatus": 0, 
-  "modified": "2013-03-19 12:52:00", 
+  "modified": "2013-03-22 18:19:36", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -189,16 +189,10 @@
  }, 
  {
   "doctype": "DocField", 
-  "fieldname": "stock_adjustment_account", 
+  "fieldname": "stock_received_but_not_billed", 
   "fieldtype": "Link", 
-  "label": "Stock Adjustment Account", 
-  "options": "Account"
- }, 
- {
-  "doctype": "DocField", 
-  "fieldname": "expenses_included_in_valuation", 
-  "fieldtype": "Link", 
-  "label": "Expenses Included In Valuation", 
+  "label": "Stock Received But Not Billed", 
+  "no_copy": 1, 
   "options": "Account"
  }, 
  {
@@ -209,19 +203,29 @@
  }, 
  {
   "doctype": "DocField", 
-  "fieldname": "stock_delivered_but_not_billed", 
+  "fieldname": "stock_adjustment_account", 
   "fieldtype": "Link", 
-  "label": "Stock Delivered But Not Billed", 
+  "label": "Stock Adjustment Account", 
+  "no_copy": 1, 
   "options": "Account"
  }, 
  {
   "doctype": "DocField", 
-  "fieldname": "stock_received_but_not_billed", 
+  "fieldname": "expenses_included_in_valuation", 
   "fieldtype": "Link", 
-  "label": "Stock Received But Not Billed", 
+  "label": "Expenses Included In Valuation", 
+  "no_copy": 1, 
   "options": "Account"
  }, 
  {
+  "doctype": "DocField", 
+  "fieldname": "stock_adjustment_cost_center", 
+  "fieldtype": "Link", 
+  "label": "Stock Adjustment Cost Center", 
+  "no_copy": 1, 
+  "options": "Cost Center"
+ }, 
+ {
   "description": "For reference only.", 
   "doctype": "DocField", 
   "fieldname": "company_info", 
diff --git a/setup/doctype/global_defaults/global_defaults.py b/setup/doctype/global_defaults/global_defaults.py
index f68a6d1..4b6707f 100644
--- a/setup/doctype/global_defaults/global_defaults.py
+++ b/setup/doctype/global_defaults/global_defaults.py
@@ -45,11 +45,20 @@
 	'session_expiry': 'session_expiry',
 	'disable_rounded_total': 'disable_rounded_total',
 	"update_stock": "update_stock",
+	# "auto_inventory_accounting": "auto_inventory_accounting",
 }
 
 class DocType:
 	def __init__(self, d, dl):
 		self.doc, self.doclist = d, dl
+		
+	def validate(self):
+		previous_auto_inventory_accounting = cint(webnotes.conn.get_value("Global Defaults", None,
+			"auto_inventory_accounting"))
+		if cint(self.doc.auto_inventory_accounting) != previous_auto_inventory_accounting:
+			from accounts.utils import create_stock_in_hand_jv
+			create_stock_in_hand_jv(reverse = \
+				cint(self.doc.auto_inventory_accounting) < previous_auto_inventory_accounting)
 
 	def on_update(self):
 		"""update defaults"""
diff --git a/stock/doctype/delivery_note_item/delivery_note_item.txt b/stock/doctype/delivery_note_item/delivery_note_item.txt
index 94c6541..ffc19c3 100644
--- a/stock/doctype/delivery_note_item/delivery_note_item.txt
+++ b/stock/doctype/delivery_note_item/delivery_note_item.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-03-07 11:42:59", 
   "docstatus": 0, 
-  "modified": "2013-03-21 18:36:22", 
+  "modified": "2013-03-22 18:43:10", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -257,10 +257,10 @@
  }, 
  {
   "doctype": "DocField", 
-  "fieldname": "cost_center", 
+  "fieldname": "purchase_cost_center", 
   "fieldtype": "Link", 
   "hidden": 1, 
-  "label": "Cost Center", 
+  "label": "Purchase Cost Center", 
   "no_copy": 1, 
   "options": "Cost Center", 
   "print_hide": 1, 
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.py b/stock/doctype/purchase_receipt/purchase_receipt.py
index 7949a1c..11c294c 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -320,7 +320,7 @@
 		
 		from accounts.general_ledger import make_gl_entries
 		
-		against_stock_account = self.get_default_account("stock_received_but_not_billed")
+		against_stock_account = self.get_company_default("stock_received_but_not_billed")
 		total_valuation_amount = self.get_total_valuation_amount()
 		gl_entries = self.get_gl_entries_for_stock(against_stock_account, total_valuation_amount)
 		
diff --git a/stock/doctype/stock_entry/stock_entry.js b/stock/doctype/stock_entry/stock_entry.js
index 447f503..dc57ec6 100644
--- a/stock/doctype/stock_entry/stock_entry.js
+++ b/stock/doctype/stock_entry/stock_entry.js
@@ -33,9 +33,9 @@
 			else account_for = "stock_adjustment_account";
 			
 			this.frm.call({
-				method: "controllers.accounts_controller.get_default_account",
+				method: "accounts.utils.get_company_default",
 				args: {
-					"account_for": account_for, 
+					"fieldname": account_for, 
 					"company": this.frm.doc.company
 				},
 				callback: function(r) {
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index f54ce60..a4a3f91 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -176,11 +176,10 @@
 		
 		from accounts.general_ledger import make_gl_entries
 		
-		cost_center = "Auto Inventory Accounting - %s" % (self.company_abbr,)
 		total_valuation_amount = self.get_total_valuation_amount()
 		
 		gl_entries = self.get_gl_entries_for_stock(self.doc.expense_adjustment_account, 
-			total_valuation_amount, cost_center=cost_center)
+			total_valuation_amount)
 		if gl_entries:
 			make_gl_entries(gl_entries, cancel=self.doc.docstatus == 2)
 				
diff --git a/stock/doctype/stock_reconciliation/stock_reconciliation.js b/stock/doctype/stock_reconciliation/stock_reconciliation.js
index 372166e..e66ae3b 100644
--- a/stock/doctype/stock_reconciliation/stock_reconciliation.js
+++ b/stock/doctype/stock_reconciliation/stock_reconciliation.js
@@ -27,9 +27,9 @@
 		
 		if (sys_defaults.auto_inventory_accounting && !this.frm.doc.expense_account) {
 			this.frm.call({
-				method: "controllers.accounts_controller.get_default_account",
+				method: "accounts.utils.get_company_default",
 				args: {
-					"account_for": "stock_adjustment_account", 
+					"fieldname": "stock_adjustment_account", 
 					"company": this.frm.doc.company
 				},
 				callback: function(r) {
diff --git a/stock/doctype/stock_reconciliation/stock_reconciliation.py b/stock/doctype/stock_reconciliation/stock_reconciliation.py
index ac0ab98..13c8ee4 100644
--- a/stock/doctype/stock_reconciliation/stock_reconciliation.py
+++ b/stock/doctype/stock_reconciliation/stock_reconciliation.py
@@ -310,11 +310,9 @@
 			msgprint(_("Please enter Expense Account"), raise_exception=1)
 			
 		from accounts.general_ledger import make_gl_entries
-		
-		cost_center = "Auto Inventory Accounting - %s" % (self.company_abbr,)
-		
+				
 		gl_entries = self.get_gl_entries_for_stock(self.doc.expense_account, 
-			self.doc.stock_value_difference, cost_center=cost_center)
+			self.doc.stock_value_difference)
 		if gl_entries:
 			make_gl_entries(gl_entries, cancel=self.doc.docstatus == 2)