aii fixes
diff --git a/accounts/doctype/pos_setting/pos_setting.js b/accounts/doctype/pos_setting/pos_setting.js
index 237615b..3ba60b4 100755
--- a/accounts/doctype/pos_setting/pos_setting.js
+++ b/accounts/doctype/pos_setting/pos_setting.js
@@ -53,4 +53,15 @@
 	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';
 }
 
+cur_frm.fields_dict["expense_account"].get_query = function(doc) {
+	return {
+		"query": "accounts.utils.get_account_list", 
+		"filters": {
+			"is_pl_account": "Yes",
+			"debit_or_credit": "Debit",
+			"company": doc.company
+		}
+	}
+}
+
 cur_frm.fields_dict.user.get_query = erpnext.utils.profile_query;
\ No newline at end of file
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.py b/accounts/doctype/purchase_invoice/purchase_invoice.py
index 85fdb47..50d5d43 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -76,7 +76,11 @@
 		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))		
+		acc_head = sql("""select name, credit_days from `tabAccount` 
+			where (name = %s or (master_name = %s and master_type = 'supplier')) 
+			and docstatus != 2 and company = %s""", 
+			(cstr(self.doc.supplier) + " - " + self.company_abbr, 
+			self.doc.supplier, self.doc.company))
 
 		ret = {}
 		if acc_head and acc_head[0][0]:
@@ -217,7 +221,8 @@
 	# 3. Is not a PL Account
 	# ----------------------------
 	def validate_credit_acc(self):
-		acc = sql("select debit_or_credit, is_pl_account from tabAccount where name = '%s'" % self.doc.credit_to)
+		acc = sql("select debit_or_credit, is_pl_account from tabAccount where name = %s", 
+			self.doc.credit_to)
 		if not acc:
 			msgprint("Account: "+ self.doc.credit_to + "does not exist")
 			raise Exception
@@ -409,7 +414,7 @@
 		purchase_controller.update_prevdoc_detail(self, is_submit = 1)
 
 
-	def make_gl_entries(self, is_cancel = 0):
+	def make_gl_entries(self):
 		from accounts.general_ledger import make_gl_entries
 		auto_inventory_accounting = \
 			cint(webnotes.defaults.get_global_default("auto_inventory_accounting"))
@@ -426,7 +431,7 @@
 					"remarks": self.doc.remarks,
 					"against_voucher": self.doc.name,
 					"against_voucher_type": self.doc.doctype,
-				}, is_cancel)
+				})
 			)
 	
 		# tax table gl entries
@@ -441,7 +446,7 @@
 						"credit": tax.add_deduct_tax == "Deduct" and tax.tax_amount or 0,
 						"remarks": self.doc.remarks,
 						"cost_center": tax.cost_center
-					}, is_cancel)
+					})
 				)
 			
 			# accumulate valuation tax
@@ -469,7 +474,7 @@
 							"debit": flt(item.valuation_rate) * flt(item.conversion_factor) \
 								*  flt(item.qty),
 							"remarks": self.doc.remarks or "Accounting Entry for Stock"
-						}, is_cancel)
+						})
 					)
 			
 			elif flt(item.amount):
@@ -481,7 +486,7 @@
 						"debit": item.amount,
 						"remarks": self.doc.remarks,
 						"cost_center": item.cost_center
-					}, is_cancel)
+					})
 				)
 				
 		if stock_item_and_auto_inventory_accounting and valuation_tax:
@@ -494,7 +499,7 @@
 					"against": self.doc.credit_to,
 					"credit": valuation_tax,
 					"remarks": self.doc.remarks or "Accounting Entry for Stock"
-				}, is_cancel)
+				})
 			)
 		
 		# writeoff account includes petty difference in the invoice amount 
@@ -507,19 +512,19 @@
 					"credit": flt(self.doc.write_off_amount),
 					"remarks": self.doc.remarks,
 					"cost_center": self.doc.write_off_cost_center
-				}, is_cancel)
+				})
 			)
 		
 		if gl_entries:
-			make_gl_entries(gl_entries, cancel=is_cancel)
+			make_gl_entries(gl_entries, cancel=(self.doc.docstatus == 2))
 
 	def on_cancel(self):
 		from accounts.utils import remove_against_link_from_jv
 		remove_against_link_from_jv(self.doc.doctype, self.doc.name, "against_voucher")
-		
-		self.make_gl_entries(is_cancel=1)
 		get_obj(dt = 'Purchase Common').update_prevdoc_detail(self, is_submit = 0)
 		
+		self.make_cancel_gl_entries()
+		
 	def on_update(self):
 		pass
 		
diff --git a/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt b/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt
index b8d9a1d..5e9daf7 100755
--- a/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt
+++ b/accounts/doctype/purchase_invoice_item/purchase_invoice_item.txt
@@ -1,8 +1,8 @@
 [
  {
-  "creation": "2013-02-27 13:45:00", 
+  "creation": "2013-03-07 11:42:55", 
   "docstatus": 0, 
-  "modified": "2013-03-07 07:03:26", 
+  "modified": "2013-03-29 13:44:37", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -35,6 +35,7 @@
   "oldfieldtype": "Link", 
   "options": "Item", 
   "print_hide": 1, 
+  "read_only": 0, 
   "reqd": 0, 
   "search_index": 1
  }, 
@@ -46,6 +47,7 @@
   "label": "Item Name", 
   "oldfieldname": "item_name", 
   "oldfieldtype": "Data", 
+  "read_only": 0, 
   "reqd": 1, 
   "search_index": 0
  }, 
@@ -57,6 +59,7 @@
   "oldfieldname": "description", 
   "oldfieldtype": "Text", 
   "print_width": "300px", 
+  "read_only": 0, 
   "width": "300px"
  }, 
  {
@@ -67,6 +70,7 @@
   "oldfieldname": "qty", 
   "oldfieldtype": "Currency", 
   "print_hide": 0, 
+  "read_only": 0, 
   "reqd": 1
  }, 
  {
@@ -75,7 +79,8 @@
   "fieldtype": "Link", 
   "label": "UOM", 
   "options": "UOM", 
-  "print_hide": 1
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -83,14 +88,16 @@
   "fieldtype": "Currency", 
   "label": "Ref Rate ", 
   "options": "currency", 
-  "print_hide": 1
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
   "fieldname": "discount_rate", 
   "fieldtype": "Float", 
   "label": "Discount %", 
-  "print_hide": 0
+  "print_hide": 0, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -101,6 +108,7 @@
   "oldfieldtype": "Currency", 
   "options": "currency", 
   "print_hide": 0, 
+  "read_only": 0, 
   "reqd": 1
  }, 
  {
@@ -120,7 +128,8 @@
   "fieldtype": "Currency", 
   "label": "Ref Rate*", 
   "options": "Company:company:default_currency", 
-  "print_hide": 1
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -131,6 +140,7 @@
   "oldfieldtype": "Currency", 
   "options": "Company:company:default_currency", 
   "print_hide": 1, 
+  "read_only": 0, 
   "reqd": 1
  }, 
  {
@@ -155,7 +165,8 @@
   "options": "Account", 
   "print_hide": 1, 
   "print_width": "120px", 
-  "reqd": 1, 
+  "read_only": 0, 
+  "reqd": 0, 
   "width": "120px"
  }, 
  {
@@ -168,6 +179,7 @@
   "options": "Cost Center", 
   "print_hide": 1, 
   "print_width": "120px", 
+  "read_only": 0, 
   "width": "120px"
  }, 
  {
@@ -177,7 +189,8 @@
   "in_filter": 1, 
   "label": "Project Name", 
   "options": "Project", 
-  "print_hide": 1
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -187,7 +200,8 @@
   "label": "Brand", 
   "oldfieldname": "brand", 
   "oldfieldtype": "Data", 
-  "print_hide": 1
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -298,7 +312,8 @@
   "fieldname": "conversion_factor", 
   "fieldtype": "Float", 
   "label": "Conversion Factor", 
-  "print_hide": 1
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -319,6 +334,7 @@
   "label": "Page Break", 
   "no_copy": 1, 
   "print_hide": 1, 
+  "read_only": 0, 
   "report_hide": 1
  }
 ]
\ No newline at end of file
diff --git a/accounts/doctype/sales_invoice/sales_invoice.js b/accounts/doctype/sales_invoice/sales_invoice.js
index 9532a54..e93a206 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/accounts/doctype/sales_invoice/sales_invoice.js
@@ -80,7 +80,8 @@
 	'total_commission', 'advances'];
 	
 	item_flds_normal = ['sales_order', 'delivery_note']
-	item_flds_pos = ['warehouse', 'serial_no', 'batch_no', 'actual_qty', 'delivered_qty']
+	item_flds_pos = ['warehouse', 'serial_no', 'batch_no', 'actual_qty', 
+		'delivered_qty', 'expense_account']
 	
 	if(cint(doc.is_pos) == 1) {
 		hide_field(par_flds);
diff --git a/accounts/doctype/sales_invoice/sales_invoice.py b/accounts/doctype/sales_invoice/sales_invoice.py
index 9b17fc0..ea6bfe2 100644
--- a/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/accounts/doctype/sales_invoice/sales_invoice.py
@@ -16,6 +16,7 @@
 
 from __future__ import unicode_literals
 import webnotes
+import webnotes.defaults
 
 from webnotes.utils import add_days, cint, cstr, date_diff, flt, getdate, nowdate, \
 	get_first_day, get_last_day
@@ -131,7 +132,7 @@
 
 		sales_com_obj.update_prevdoc_detail(0, self)
 		
-		self.make_gl_entries()
+		self.make_cancel_gl_entries()
 		
 	def on_update_after_submit(self):
 		self.validate_recurring_invoice()
diff --git a/accounts/utils.py b/accounts/utils.py
index d6b2043..755546c 100644
--- a/accounts/utils.py
+++ b/accounts/utils.py
@@ -264,48 +264,61 @@
 	from webnotes.utils import nowdate
 	today = nowdate()
 	fiscal_year = get_fiscal_year(today)[0]
+	jv_list = []
 	
 	for company in webnotes.conn.sql_list("select name from `tabCompany`"):
 		stock_rbnb_value = get_stock_rbnb_value(company)
+		stock_rbnb_value = reverse and -1*stock_rbnb_value or stock_rbnb_value
+		if stock_rbnb_value:
+			jv = webnotes.bean([
+				{
+					"doctype": "Journal Voucher",
+					"naming_series": "_PATCH-",
+					"company": company,
+					"posting_date": today,
+					"fiscal_year": fiscal_year,
+					"voucher_type": "Journal Entry",
+					"user_remark": "Accounting Entry for Stock: \
+						Initial booking of stock received but not billed account"
+				},
+				{
+					"doctype": "Journal Voucher Detail",
+					"parentfield": "entries",
+					"account": get_company_default(company, "stock_received_but_not_billed"),
+					(stock_rbnb_value > 0 and "credit" or "debit"): abs(stock_rbnb_value)
+				},
+				{
+					"doctype": "Journal Voucher Detail",
+					"parentfield": "entries",
+					"account": get_company_default(company, "stock_adjustment_account"),
+					(stock_rbnb_value > 0 and "debit" or "credit"): abs(stock_rbnb_value),
+					"cost_center": get_company_default(company, "stock_adjustment_cost_center")
+				},
+			])
+			jv.insert()
+			jv.submit()
+			
+			jv_list.append(jv.doc.name)
+	
+	if jv_list:
+		webnotes.msgprint("""Folowing Journal Vouchers has been created automatically: 
+			%s""" % '\n'.join(jv_list))
+			
+	webnotes.msgprint("""Please refresh the system to get effect of Auto Inventory Accounting""")
+			
 		
-		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_rate*qty) 
+def get_stock_rbnb_value(company):
+	total_received_amount = webnotes.conn.sql("""select sum(valuation_rate*qty*conversion_factor) 
 		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 exists(select name from `tabPurchase Receipt` 
 			where name = pr_item.parent and company = %s)""", company)
 		
-	total_billed_amount = webnotes.conn.sql("""select sum(valuation_rate*qty) 
+	total_billed_amount = webnotes.conn.sql("""select sum(valuation_rate*qty*conversion_factor) 
 		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 exists(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/controllers/selling_controller.py b/controllers/selling_controller.py
index f3fb47f..b22042d 100644
--- a/controllers/selling_controller.py
+++ b/controllers/selling_controller.py
@@ -41,9 +41,10 @@
 			self.doc.in_words_export = money_in_words(disable_rounded_total and 
 				self.doc.grand_total_export or self.doc.rounded_total_export, self.doc.currency)
 
-	def set_buying_amount(self):
+	def set_buying_amount(self, stock_ledger_entries = None):
 		from stock.utils import get_buying_amount
-		stock_ledger_entries = self.get_stock_ledger_entries()
+		if not stock_ledger_entries:
+			stock_ledger_entries = self.get_stock_ledger_entries()
 
 		item_sales_bom = {}
 		for d in self.doclist.get({"parentfield": "packing_details"}):
@@ -65,4 +66,8 @@
 	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)
+				
+		if item.buying_amount and not item.cost_center:
+			msgprint(_("""Cost Center 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 89f62aa..7cfb68c 100644
--- a/controllers/stock_controller.py
+++ b/controllers/stock_controller.py
@@ -16,7 +16,8 @@
 
 from __future__ import unicode_literals
 import webnotes
-from webnotes import msgprint, _
+from webnotes.utils import cint
+import webnotes.defaults
 from controllers.accounts_controller import AccountsController
 
 class StockController(AccountsController):
@@ -72,4 +73,10 @@
 			item_list.append(item.item_code)
 			warehouse_list.append(item.warehouse)
 			
-		return list(set(item_list)), list(set(warehouse_list))
\ No newline at end of file
+		return list(set(item_list)), list(set(warehouse_list))
+		
+	def make_cancel_gl_entries(self):
+		if webnotes.conn.sql("""select name from `tabGL Entry` where voucher_type=%s 
+			and voucher_no=%s and ifnull(is_cancelled, 'No')='No'""",
+			(self.doc.doctype, self.doc.name)):
+				self.make_gl_entries()
\ No newline at end of file
diff --git a/hr/doctype/leave_control_panel/leave_control_panel.py b/hr/doctype/leave_control_panel/leave_control_panel.py
index d26efd4..e771c5c 100644
--- a/hr/doctype/leave_control_panel/leave_control_panel.py
+++ b/hr/doctype/leave_control_panel/leave_control_panel.py
@@ -17,10 +17,8 @@
 from __future__ import unicode_literals
 import webnotes
 
-from webnotes.utils import cint, cstr, flt, now, nowdate
-from webnotes.model import db_exists
+from webnotes.utils import cint, cstr, flt, nowdate
 from webnotes.model.doc import Document
-from webnotes.model.bean import copy_doclist
 from webnotes.model.code import get_obj
 from webnotes import msgprint
 
@@ -49,7 +47,7 @@
     emp_query = "select name from `tabEmployee` "
     if flag == 1:
       emp_query += condition 
-    e = sql(emp_query, debug=1)
+    e = sql(emp_query)
     return e
 
   # ----------------
diff --git a/manufacturing/doctype/bom/bom.py b/manufacturing/doctype/bom/bom.py
index ef07e5e..75bf305 100644
--- a/manufacturing/doctype/bom/bom.py
+++ b/manufacturing/doctype/bom/bom.py
@@ -17,7 +17,7 @@
 from __future__ import unicode_literals
 import webnotes
 from webnotes.utils import cint, cstr, flt, now, nowdate
-from webnotes.model.doc import Document, addchild
+from webnotes.model.doc import addchild
 from webnotes.model.bean import getlist
 from webnotes.model.code import get_obj
 from webnotes import msgprint, _
@@ -76,7 +76,7 @@
 
 	def get_item_details(self, item_code):
 		res = sql("""select description, stock_uom as uom
-			from `tabItem` where item_code = %s""", item_code, as_dict = 1, debug=1)
+			from `tabItem` where item_code = %s""", item_code, as_dict = 1)
 		return res and res[0] or {}
 
 	def get_workstation_details(self,workstation):
diff --git a/patches/march_2013/p03_update_buying_amount.py b/patches/march_2013/p03_update_buying_amount.py
index ae0c5ea..e4a3fcb 100644
--- a/patches/march_2013/p03_update_buying_amount.py
+++ b/patches/march_2013/p03_update_buying_amount.py
@@ -1,10 +1,30 @@
 import webnotes
+from webnotes.utils import now_datetime
 
 def execute():
-	dn_list = webnotes.conn.sql("""select name from `tabDelivery Note` where docstatus < 2""")
-	for dn in dn_list:
-		webnotes.bean("Delivery Note", dn[0]).run_method("set_buying_amount")
+	webnotes.conn.auto_commit_on_many_writes = True
+	for company in webnotes.conn.sql("select name from `tabCompany`"):
+		print company[0]
+		stock_ledger_entries = webnotes.conn.sql("""select item_code, voucher_type, voucher_no,
+			voucher_detail_no, posting_date, posting_time, stock_value, 
+			warehouse, actual_qty as qty from `tabStock Ledger Entry` 
+			where ifnull(`is_cancelled`, "No") = "No" and company = %s
+			order by item_code desc, warehouse desc, 
+			posting_date desc, posting_time desc, name desc""", company[0], as_dict=True)
 		
-	si_list = webnotes.conn.sql("""select name from `tabSales Invoice` where docstatus < 2""")
-	for si in si_list:
-		webnotes.bean("Sales Invoice", si[0]).run_method("set_buying_amount")
\ No newline at end of file
+		dn_list = webnotes.conn.sql("""select name from `tabDelivery Note` 
+			where docstatus < 2 and company = %s""", company[0])
+		print "Total Delivery Note: ", len(dn_list)
+		
+		for dn in dn_list:
+			dn = webnotes.get_obj("Delivery Note", dn[0], with_children = 1)
+			dn.set_buying_amount(stock_ledger_entries)
+		
+		si_list = webnotes.conn.sql("""select name from `tabSales Invoice` 
+			where docstatus < 2	and company = %s""", company[0])
+		print "Total Sales Invoice: ", len(si_list)
+		for si in si_list:
+			si = webnotes.get_obj("Sales Invoice", si[0], with_children = 1)
+			si.set_buying_amount(stock_ledger_entries)
+		
+	webnotes.conn.auto_commit_on_many_writes = False
\ No newline at end of file
diff --git a/patches/march_2013/p07_update_valuation_rate.py b/patches/march_2013/p07_update_valuation_rate.py
index 51e556b..7d11e42 100644
--- a/patches/march_2013/p07_update_valuation_rate.py
+++ b/patches/march_2013/p07_update_valuation_rate.py
@@ -2,12 +2,12 @@
 
 def execute():
 	for purchase_invoice in webnotes.conn.sql_list("""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
+		from `tabPurchase Invoice Item` pi_item where docstatus = 1 and ifnull(valuation_rate, 0)=0 
+		and exists(select name from `tabPurchase Invoice` where name = pi_item.parent)"""):
+			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/patches/march_2013/p08_create_aii_accounts.py b/patches/march_2013/p08_create_aii_accounts.py
index ff53d8b..f6e1e2d 100644
--- a/patches/march_2013/p08_create_aii_accounts.py
+++ b/patches/march_2013/p08_create_aii_accounts.py
@@ -2,6 +2,7 @@
 def execute():
 	add_group_accounts()
 	add_ledger_accounts()
+	add_aii_cost_center()
 	
 def _check(parent_account, company):
 	def _get_root(is_pl_account, debit_or_credit):
@@ -34,7 +35,6 @@
 def add_ledger_accounts():
 	accounts_to_add = [
 		["Stock In Hand", "Stock Assets", "Ledger", ""],
-		["Stock Debit But Not Billed", "Stock Assets", "Ledger", ""],
 		["Cost of Goods Sold", "Stock Expenses", "Ledger", "Expense Account"],
 		["Stock Adjustment", "Stock Expenses", "Ledger", "Expense Account"],
 		["Expenses Included In Valuation", "Stock Expenses", "Ledger", "Expense Account"],
@@ -58,4 +58,21 @@
 					"account_type": account_type,
 					"company": company
 				})
-				account.insert()
\ No newline at end of file
+				account.insert()
+				
+def add_aii_cost_center():
+	for company, abbr in webnotes.conn.sql("""select name, abbr from `tabCompany`"""):
+		if not webnotes.conn.exists("Cost Center", "Auto Inventory Accounting - %s" % abbr):
+			parent_cost_center = webnotes.conn.get_value("Cost Center", 
+				{"parent_cost_center['']": '', "company_name": company}, 'name')
+			
+			cc = webnotes.bean({
+				"doctype": "Cost Center",
+				"cost_center_name": "Auto Inventory Accounting",
+				"parent_cost_center": parent_cost_center,
+				"group_or_ledger": "Ledger",
+				"company_name": company
+			})
+			cc.insert()
+				
+				
\ No newline at end of file
diff --git a/patches/patch_list.py b/patches/patch_list.py
index 905ea29..08d936d 100644
--- a/patches/patch_list.py
+++ b/patches/patch_list.py
@@ -227,4 +227,7 @@
 	"patches.march_2013.p10_update_against_expense_account",
 	"patches.march_2013.p11_update_attach_files",
 	"patches.march_2013.p12_set_item_tax_rate_in_json",
+	"patches.march_2013.p07_update_valuation_rate",
+	"patches.march_2013.p08_create_aii_accounts",
+	"patches.march_2013.p03_update_buying_amount",
 ]
\ 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 729013f..dde4919 100644
--- a/selling/doctype/sales_common/sales_common.py
+++ b/selling/doctype/sales_common/sales_common.py
@@ -361,7 +361,7 @@
 		sales_team_list = obj.doclist.get({"parentfield": "sales_team"})
 		total_allocation = sum([flt(d.allocated_percentage) for d in sales_team_list])
 		if sales_team_list and total_allocation != 100.0:
-			msgprint("Total Allocated %% of Sales Persons should be 100%", raise_exception=True)
+			msgprint("Total Allocated % of Sales Persons should be 100%", raise_exception=True)
 			
 	# Check Conversion Rate (i.e. it will not allow conversion rate to be 1 for Currency other than default currency set in Global Defaults)
 	# ===========================================================================
diff --git a/setup/doctype/company/company.js b/setup/doctype/company/company.js
index 5e78b79..463b922 100644
--- a/setup/doctype/company/company.js
+++ b/setup/doctype/company/company.js
@@ -89,9 +89,6 @@
 cur_frm.fields_dict["expenses_included_in_valuation"].get_query = 
 	cur_frm.fields_dict["stock_adjustment_account"].get_query;
 	
-cur_frm.fields_dict["stock_delivered_but_not_billed"].get_query = 
-	cur_frm.fields_dict["stock_in_hand_account"].get_query;
-
 cur_frm.fields_dict["stock_received_but_not_billed"].get_query = function(doc) {
 	return {
 		"query": "accounts.utils.get_account_list", 
@@ -106,6 +103,6 @@
 cur_frm.fields_dict["stock_adjustment_cost_center"].get_query = function(doc) {
 	return {
 		"query": "accounts.utils.get_cost_center_list", 
-		"filters": {"company": doc.name}
+		"filters": {"company_name": doc.name}
 	}
 }
\ No newline at end of file
diff --git a/setup/doctype/company/company.py b/setup/doctype/company/company.py
index 47b250d..bee1333 100644
--- a/setup/doctype/company/company.py
+++ b/setup/doctype/company/company.py
@@ -49,8 +49,6 @@
 						['Earnest Money','Securities and Deposits','Ledger','No','','Debit',self.doc.name,''],
 					['Stock Assets','Current Assets','Group','No','','Debit',self.doc.name,''],
 						['Stock In Hand','Stock Assets','Ledger','No','','Debit',self.doc.name,''],
-						['Stock Delivered But Not Billed', 'Stock Assets', 'Ledger', 
-							'No', '', 'Debit', self.doc.name, ''],
 					['Tax Assets','Current Assets','Group','No','','Debit',self.doc.name,''],
 				['Fixed Assets','Application of Funds (Assets)','Group','No','','Debit',self.doc.name,''],
 					['Capital Equipments','Fixed Assets','Ledger','No','Fixed Asset Account','Debit',self.doc.name,''],
diff --git a/setup/doctype/company/company.txt b/setup/doctype/company/company.txt
index feb3bca..a49a7e0 100644
--- a/setup/doctype/company/company.txt
+++ b/setup/doctype/company/company.txt
@@ -1,8 +1,8 @@
 [
  {
-  "creation": "2013-03-21 17:41:00", 
+  "creation": "2013-03-26 11:03:08", 
   "docstatus": 0, 
-  "modified": "2013-03-25 15:35:34", 
+  "modified": "2013-03-28 16:04:27", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -25,14 +25,19 @@
  }, 
  {
   "amend": 0, 
+  "cancel": 1, 
+  "create": 1, 
   "doctype": "DocPerm", 
   "name": "__common__", 
   "parent": "Company", 
   "parentfield": "permissions", 
   "parenttype": "DocType", 
+  "permlevel": 0, 
   "read": 1, 
   "report": 1, 
-  "submit": 0
+  "role": "System Manager", 
+  "submit": 0, 
+  "write": 1
  }, 
  {
   "doctype": "DocType", 
@@ -43,7 +48,8 @@
   "fieldname": "details", 
   "fieldtype": "Section Break", 
   "label": "Company Details", 
-  "oldfieldtype": "Section Break"
+  "oldfieldtype": "Section Break", 
+  "read_only": 0
  }, 
  {
   "description": "Please Enter Abbreviation or Short Name properly as it will be added as Suffix to all Account Heads.", 
@@ -54,12 +60,14 @@
   "no_copy": 0, 
   "oldfieldname": "abbr", 
   "oldfieldtype": "Data", 
+  "read_only": 0, 
   "reqd": 1
  }, 
  {
   "doctype": "DocField", 
   "fieldname": "cb0", 
-  "fieldtype": "Column Break"
+  "fieldtype": "Column Break", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -69,6 +77,7 @@
   "no_copy": 0, 
   "oldfieldname": "company_name", 
   "oldfieldtype": "Data", 
+  "read_only": 0, 
   "reqd": 1
  }, 
  {
@@ -76,7 +85,8 @@
   "fieldname": "default_settings", 
   "fieldtype": "Section Break", 
   "label": "Default Settings", 
-  "oldfieldtype": "Section Break"
+  "oldfieldtype": "Section Break", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -84,6 +94,7 @@
   "fieldtype": "Link", 
   "label": "Default Currency", 
   "options": "Currency", 
+  "read_only": 0, 
   "reqd": 1
  }, 
  {
@@ -95,14 +106,16 @@
   "no_copy": 1, 
   "oldfieldname": "default_bank_account", 
   "oldfieldtype": "Link", 
-  "options": "Account"
+  "options": "Account", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
   "fieldname": "default_cash_account", 
   "fieldtype": "Link", 
   "label": "Default Cash Account", 
-  "options": "Account"
+  "options": "Account", 
+  "read_only": 0
  }, 
  {
   "depends_on": "eval:!doc.__islocal", 
@@ -113,7 +126,8 @@
   "no_copy": 1, 
   "oldfieldname": "receivables_group", 
   "oldfieldtype": "Link", 
-  "options": "Account"
+  "options": "Account", 
+  "read_only": 0
  }, 
  {
   "depends_on": "eval:!doc.__islocal", 
@@ -124,13 +138,15 @@
   "no_copy": 1, 
   "oldfieldname": "payables_group", 
   "oldfieldtype": "Link", 
-  "options": "Account"
+  "options": "Account", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
   "fieldname": "column_break0", 
   "fieldtype": "Column Break", 
   "oldfieldtype": "Column Break", 
+  "read_only": 0, 
   "width": "50%"
  }, 
  {
@@ -140,7 +156,8 @@
   "fieldtype": "Int", 
   "label": "Credit Days", 
   "oldfieldname": "credit_days", 
-  "oldfieldtype": "Int"
+  "oldfieldtype": "Int", 
+  "read_only": 0
  }, 
  {
   "depends_on": "eval:!doc.__islocal", 
@@ -150,7 +167,8 @@
   "label": "Credit Limit", 
   "oldfieldname": "credit_limit", 
   "oldfieldtype": "Currency", 
-  "options": "default_currency"
+  "options": "default_currency", 
+  "read_only": 0
  }, 
  {
   "depends_on": "eval:!doc.__islocal", 
@@ -160,7 +178,8 @@
   "label": "If Yearly Budget Exceeded", 
   "oldfieldname": "yearly_bgt_flag", 
   "oldfieldtype": "Select", 
-  "options": "\nWarn\nIgnore\nStop"
+  "options": "\nWarn\nIgnore\nStop", 
+  "read_only": 0
  }, 
  {
   "depends_on": "eval:!doc.__islocal", 
@@ -170,14 +189,16 @@
   "label": "If Monthly Budget Exceeded", 
   "oldfieldname": "monthly_bgt_flag", 
   "oldfieldtype": "Select", 
-  "options": "\nWarn\nIgnore\nStop"
+  "options": "\nWarn\nIgnore\nStop", 
+  "read_only": 0
  }, 
  {
-  "depends_on": "eval:!doc.__islocal && sys_defaults.auto_inventory_accounting", 
+  "depends_on": "eval:!doc.__islocal", 
   "doctype": "DocField", 
   "fieldname": "auto_inventory_accounting_settings", 
   "fieldtype": "Section Break", 
-  "label": "Auto Inventory Accounting Settings"
+  "label": "Auto Inventory Accounting Settings", 
+  "read_only": 0
  }, 
  {
   "description": "This account will be used to maintain value of available stock", 
@@ -195,12 +216,14 @@
   "fieldtype": "Link", 
   "label": "Stock Received But Not Billed", 
   "no_copy": 1, 
-  "options": "Account"
+  "options": "Account", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
   "fieldname": "col_break23", 
   "fieldtype": "Column Break", 
+  "read_only": 0, 
   "width": "50%"
  }, 
  {
@@ -209,7 +232,8 @@
   "fieldtype": "Link", 
   "label": "Stock Adjustment Account", 
   "no_copy": 1, 
-  "options": "Account"
+  "options": "Account", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -217,7 +241,8 @@
   "fieldtype": "Link", 
   "label": "Expenses Included In Valuation", 
   "no_copy": 1, 
-  "options": "Account"
+  "options": "Account", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -225,14 +250,16 @@
   "fieldtype": "Link", 
   "label": "Stock Adjustment Cost Center", 
   "no_copy": 1, 
-  "options": "Cost Center"
+  "options": "Cost Center", 
+  "read_only": 0
  }, 
  {
   "description": "For reference only.", 
   "doctype": "DocField", 
   "fieldname": "company_info", 
   "fieldtype": "Section Break", 
-  "label": "Company Info"
+  "label": "Company Info", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -240,13 +267,15 @@
   "fieldtype": "Small Text", 
   "label": "Address", 
   "oldfieldname": "address", 
-  "oldfieldtype": "Small Text"
+  "oldfieldtype": "Small Text", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
   "fieldname": "column_break1", 
   "fieldtype": "Column Break", 
   "oldfieldtype": "Column Break", 
+  "read_only": 0, 
   "width": "50%"
  }, 
  {
@@ -256,7 +285,8 @@
   "label": "Phone No", 
   "oldfieldname": "phone_no", 
   "oldfieldtype": "Data", 
-  "options": "Phone"
+  "options": "Phone", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -265,7 +295,8 @@
   "label": "Fax", 
   "oldfieldname": "fax", 
   "oldfieldtype": "Data", 
-  "options": "Phone"
+  "options": "Phone", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -274,7 +305,8 @@
   "label": "Email", 
   "oldfieldname": "email", 
   "oldfieldtype": "Data", 
-  "options": "Email"
+  "options": "Email", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -282,7 +314,8 @@
   "fieldtype": "Data", 
   "label": "Website", 
   "oldfieldname": "website", 
-  "oldfieldtype": "Data"
+  "oldfieldtype": "Data", 
+  "read_only": 0
  }, 
  {
   "description": "Company registration numbers for your reference. Example: VAT Registration Numbers etc.", 
@@ -291,6 +324,7 @@
   "fieldtype": "Section Break", 
   "label": "Registration Info", 
   "oldfieldtype": "Section Break", 
+  "read_only": 0, 
   "width": "50%"
  }, 
  {
@@ -300,7 +334,8 @@
   "fieldtype": "Code", 
   "label": "Registration Details", 
   "oldfieldname": "registration_details", 
-  "oldfieldtype": "Code"
+  "oldfieldtype": "Code", 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -313,19 +348,6 @@
   "read_only": 1
  }, 
  {
-  "cancel": 1, 
-  "create": 1, 
-  "doctype": "DocPerm", 
-  "permlevel": 0, 
-  "role": "System Manager", 
-  "write": 1
- }, 
- {
-  "cancel": 0, 
-  "create": 0, 
-  "doctype": "DocPerm", 
-  "permlevel": 1, 
-  "role": "All", 
-  "write": 0
+  "doctype": "DocPerm"
  }
 ]
\ No newline at end of file
diff --git a/setup/doctype/global_defaults/global_defaults.py b/setup/doctype/global_defaults/global_defaults.py
index 3f8de1d..8275513 100644
--- a/setup/doctype/global_defaults/global_defaults.py
+++ b/setup/doctype/global_defaults/global_defaults.py
@@ -62,7 +62,6 @@
 
 	def on_update(self):
 		"""update defaults"""
-		
 		self.validate_session_expiry()
 		
 		for key in keydict:
diff --git a/stock/doctype/delivery_note/delivery_note.js b/stock/doctype/delivery_note/delivery_note.js
index 61df6b0..8870832 100644
--- a/stock/doctype/delivery_note/delivery_note.js
+++ b/stock/doctype/delivery_note/delivery_note.js
@@ -74,6 +74,11 @@
 	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);
 }
 
 
diff --git a/stock/doctype/delivery_note/delivery_note.py b/stock/doctype/delivery_note/delivery_note.py
index daf7d61..90e5bdf 100644
--- a/stock/doctype/delivery_note/delivery_note.py
+++ b/stock/doctype/delivery_note/delivery_note.py
@@ -21,6 +21,8 @@
 from webnotes.model.bean import getlist
 from webnotes.model.code import get_obj
 from webnotes import msgprint
+import webnotes.defaults
+
 
 sql = webnotes.conn.sql
 
@@ -312,7 +314,7 @@
 		webnotes.conn.set(self.doc, 'status', 'Cancelled')
 		self.cancel_packing_slips()
 		
-		self.make_gl_entries()
+		self.make_cancel_gl_entries()
 
 
 	def check_next_docstatus(self):
diff --git a/stock/doctype/purchase_receipt/purchase_receipt.py b/stock/doctype/purchase_receipt/purchase_receipt.py
index 7bc470d..8e81fa5 100644
--- a/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -21,6 +21,7 @@
 from webnotes.model.bean import getlist
 from webnotes.model.code import get_obj
 from webnotes import msgprint
+import webnotes.defaults
 
 sql = webnotes.conn.sql
 
@@ -290,7 +291,7 @@
 		# 6. Update last purchase rate
 		pc_obj.update_last_purchase_rate(self, 0)
 		
-		self.make_gl_entries()
+		self.make_cancel_gl_entries()
 
 	def bk_flush_supp_wh(self, is_submit):
 		for d in getlist(self.doclist, 'pr_raw_material_details'):
@@ -326,7 +327,7 @@
 		gl_entries = self.get_gl_entries_for_stock(against_stock_account, total_valuation_amount)
 		
 		if gl_entries:
-			make_gl_entries(gl_entries, cancel=self.doc.docstatus == 2)
+			make_gl_entries(gl_entries, cancel=(self.doc.docstatus == 2))
 		
 	def get_total_valuation_amount(self):
 		total_valuation_amount = 0.0
diff --git a/stock/doctype/serial_no/serial_no.py b/stock/doctype/serial_no/serial_no.py
index 5b15977..65bd2dd 100644
--- a/stock/doctype/serial_no/serial_no.py
+++ b/stock/doctype/serial_no/serial_no.py
@@ -19,7 +19,7 @@
 
 from webnotes.utils import cint, getdate, nowdate
 import datetime
-from webnotes import msgprint, _
+from webnotes import msgprint
 	
 from controllers.stock_controller import StockController
 
@@ -103,7 +103,12 @@
 		elif self.doc.status == 'In Store': 
 			webnotes.conn.set(self.doc, 'status', 'Not in Use')
 			self.make_stock_ledger_entry(-1)
-			self.make_gl_entries(cancel=True)
+			
+			if cint(webnotes.defaults.get_global_default("auto_inventory_accounting")) \
+				and webnotes.conn.sql("""select name from `tabGL Entry`
+				where voucher_type=%s and voucher_no=%s and ifnull(is_cancelled, 'No')='No'""",
+				(self.doc.doctype, self.doc.name)):
+					self.make_gl_entries(cancel=True)
 
 
 	def on_cancel(self):
diff --git a/stock/doctype/stock_entry/stock_entry.js b/stock/doctype/stock_entry/stock_entry.js
index 9b89d78..339c945 100644
--- a/stock/doctype/stock_entry/stock_entry.js
+++ b/stock/doctype/stock_entry/stock_entry.js
@@ -77,7 +77,7 @@
 		};
 		
 		if (sys_defaults.auto_inventory_accounting) {
-			this.frm.add_fetch("company", "expense_adjustment_account", "stock_adjustment_account");
+			this.frm.add_fetch("company", "stock_adjustment_account", "expense_adjustment_account");
 
 			this.frm.fields_dict["expense_adjustment_account"].get_query = function() {
 				return {
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index a176188..fa60072 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -16,6 +16,7 @@
 
 from __future__ import unicode_literals
 import webnotes
+import webnotes.defaults
 
 from webnotes.utils import cstr, cint, flt, comma_or
 from webnotes.model.doc import Document, addchild
@@ -67,7 +68,7 @@
 		self.update_serial_no(0)
 		self.update_stock_ledger(1)
 		self.update_production_order(0)
-		self.make_gl_entries()
+		self.make_cancel_gl_entries()
 		
 	def validate_fiscal_year(self):
 		import accounts.utils
@@ -426,16 +427,18 @@
 		
 	def get_warehouse_details(self, args):
 		args = json.loads(args)
-		args.update({
-			"posting_date": self.doc.posting_date,
-			"posting_time": self.doc.posting_time,
-		})
-		args = webnotes._dict(args)
+		ret = {}
+		if args.get('warehouse') and args.get('item_code'):
+			args.update({
+				"posting_date": self.doc.posting_date,
+				"posting_time": self.doc.posting_time,
+			})
+			args = webnotes._dict(args)
 		
-		ret = {
-			"actual_qty" : get_previous_sle(args).get("qty_after_transaction") or 0,
-			"incoming_rate" : self.get_incoming_rate(args)
-		}
+			ret = {
+				"actual_qty" : get_previous_sle(args).get("qty_after_transaction") or 0,
+				"incoming_rate" : self.get_incoming_rate(args)
+			}
 		return ret
 		
 	def get_items(self):
diff --git a/stock/doctype/stock_entry/stock_entry.txt b/stock/doctype/stock_entry/stock_entry.txt
index 91f9bb4..fef710b 100644
--- a/stock/doctype/stock_entry/stock_entry.txt
+++ b/stock/doctype/stock_entry/stock_entry.txt
@@ -1,8 +1,8 @@
 [
  {
-  "creation": "2013-03-26 06:51:17", 
+  "creation": "2013-03-28 15:56:40", 
   "docstatus": 0, 
-  "modified": "2013-03-26 07:24:53", 
+  "modified": "2013-03-29 15:31:42", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -116,6 +116,7 @@
   "oldfieldtype": "Link", 
   "options": "Delivery Note", 
   "print_hide": 1, 
+  "read_only": 0, 
   "report_hide": 0, 
   "reqd": 0, 
   "search_index": 1
@@ -129,7 +130,8 @@
   "label": "Sales Invoice No", 
   "no_copy": 1, 
   "options": "Sales Invoice", 
-  "print_hide": 1
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "allow_on_submit": 0, 
@@ -145,6 +147,7 @@
   "oldfieldtype": "Link", 
   "options": "Purchase Receipt", 
   "print_hide": 1, 
+  "read_only": 0, 
   "report_hide": 0, 
   "reqd": 0, 
   "search_index": 1
@@ -201,7 +204,9 @@
   "fieldname": "expense_adjustment_account", 
   "fieldtype": "Link", 
   "label": "Expense/Adjustment Account", 
-  "options": "Account"
+  "options": "Account", 
+  "print_hide": 1, 
+  "read_only": 0
  }, 
  {
   "doctype": "DocField", 
@@ -550,6 +555,7 @@
   "label": "Fiscal Year", 
   "options": "link:Fiscal Year", 
   "print_hide": 1, 
+  "read_only": 0, 
   "reqd": 1
  }, 
  {
@@ -620,5 +626,13 @@
  {
   "doctype": "DocPerm", 
   "role": "Manufacturing User"
+ }, 
+ {
+  "doctype": "DocPerm", 
+  "role": "Manufacturing Manager"
+ }, 
+ {
+  "doctype": "DocPerm", 
+  "role": "Material Manager"
  }
 ]
\ No newline at end of file
diff --git a/stock/doctype/stock_reconciliation/stock_reconciliation.py b/stock/doctype/stock_reconciliation/stock_reconciliation.py
index 5604179..9aa2916 100644
--- a/stock/doctype/stock_reconciliation/stock_reconciliation.py
+++ b/stock/doctype/stock_reconciliation/stock_reconciliation.py
@@ -16,6 +16,7 @@
 
 from __future__ import unicode_literals
 import webnotes
+import webnotes.defaults
 import json
 from webnotes import msgprint, _
 from webnotes.utils import cstr, flt, cint
@@ -37,7 +38,7 @@
 		
 	def on_cancel(self):
 		self.delete_stock_ledger_entries()
-		self.make_gl_entries()
+		self.make_cancel_gl_entries()
 		
 	def validate_data(self):
 		if not self.doc.reconciliation_json: