Merge branch 'master' of github.com:webnotes/erpnext
diff --git a/accounts/page/accounts_browser/accounts_browser.js b/accounts/page/accounts_browser/accounts_browser.js
index 904b4cd..30ed5b9 100644
--- a/accounts/page/accounts_browser/accounts_browser.js
+++ b/accounts/page/accounts_browser/accounts_browser.js
@@ -80,7 +80,7 @@
 			$.each(r.message, function(i, v) {
 				$('<option>').html(v).attr('value', v).appendTo(wrapper.$company_select);
 			});
-			wrapper.$company_select.val(sys_defaults.company || r[0]).change();
+			wrapper.$company_select.val(wn.defaults.get_default("company") || r[0]).change();
 		}
 	});
 }
diff --git a/accounts/report/accounts_payable/accounts_payable.js b/accounts/report/accounts_payable/accounts_payable.js
index 7ee38f2..05627d4 100644
--- a/accounts/report/accounts_payable/accounts_payable.js
+++ b/accounts/report/accounts_payable/accounts_payable.js
@@ -5,7 +5,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		},
 		{
 			"fieldname":"account",
diff --git a/accounts/report/accounts_receivable/accounts_receivable.js b/accounts/report/accounts_receivable/accounts_receivable.js
index 68c8593..0ed1656 100644
--- a/accounts/report/accounts_receivable/accounts_receivable.js
+++ b/accounts/report/accounts_receivable/accounts_receivable.js
@@ -5,7 +5,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		},
 		{
 			"fieldname":"account",
diff --git a/accounts/report/budget_variance_report/budget_variance_report.js b/accounts/report/budget_variance_report/budget_variance_report.js
index a051605..51a583e 100644
--- a/accounts/report/budget_variance_report/budget_variance_report.js
+++ b/accounts/report/budget_variance_report/budget_variance_report.js
@@ -19,7 +19,7 @@
 			label: "Company",
 			fieldtype: "Link",
 			options: "Company",
-			default: sys_defaults.company
+			default: wn.defaults.get_default("company")
 		},
 	]
 }
\ No newline at end of file
diff --git a/accounts/report/item_wise_purchase_register/item_wise_purchase_register.js b/accounts/report/item_wise_purchase_register/item_wise_purchase_register.js
index 8323a1a..0805fe5 100644
--- a/accounts/report/item_wise_purchase_register/item_wise_purchase_register.js
+++ b/accounts/report/item_wise_purchase_register/item_wise_purchase_register.js
@@ -25,15 +25,24 @@
 			"fieldtype": "Link",
 			"options": "Account",
 			"get_query": function() {
+				var company = wn.query_report.filters_by_name.company.get_value();
 				return {
 					"query": "accounts.utils.get_account_list", 
 					"filters": {
 						"is_pl_account": "No",
 						"debit_or_credit": "Credit",
+						"company": company,
 						"master_type": "Supplier"
 					}
 				}
 			}
+		},
+		{
+			"fieldname":"company",
+			"label": "Company",
+			"fieldtype": "Link",
+			"options": "Company",
+			"default": wn.defaults.get_default("company")
 		}
 	]
 }
\ No newline at end of file
diff --git a/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py b/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
index 9f5f071..3840837 100644
--- a/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
+++ b/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
@@ -16,19 +16,28 @@
 
 from __future__ import unicode_literals
 import webnotes
+from webnotes.utils import flt
 
 def execute(filters=None):
 	if not filters: filters = {}
-	
 	columns = get_columns()
+	last_col = len(columns) - 1
+	
 	item_list = get_items(filters)
 	aii_account_map = get_aii_accounts()
+	item_tax, tax_accounts = get_tax_accounts(item_list, columns)
+	
 	data = []
 	for d in item_list:
 		expense_head = d.expense_head or aii_account_map.get(d.company)
-		data.append([d.item_code, d.item_name, d.item_group, d.name, d.posting_date, 
+		row = [d.item_code, d.item_name, d.item_group, d.parent, d.posting_date, 
 			d.supplier_name, d.credit_to, d.project_name, d.company, d.purchase_order, 
-			d.purchase_receipt, expense_head, d.qty, d.rate, d.amount])
+			d.purchase_receipt, expense_head, d.qty, d.rate, d.amount]
+		for tax in tax_accounts:
+			row.append(item_tax.get(d.parent, {}).get(d.item_code, {}).get(tax, 0))
+			
+		row.append(sum(row[last_col:]))
+		data.append(row)
 	
 	return columns, data
 	
@@ -41,33 +50,60 @@
 		"Expense Account:Link/Account:140", "Qty:Float:120", "Rate:Currency:120", 
 		"Amount:Currency:120"]
 	
-	
 def get_conditions(filters):
 	conditions = ""
 	
-	if filters.get("account"): conditions += " and pi.credit_to = %(account)s"
-	
-	if filters.get("item_code"): conditions += " and pi_item.item_code = %(item_code)s"
-
-	if filters.get("from_date"): conditions += " and pi.posting_date>=%(from_date)s"
-	if filters.get("to_date"): conditions += " and pi.posting_date<=%(to_date)s"
+	for opts in (("company", " and company=%(company)s"),
+		("account", " and pi.credit_to = %(account)s"),
+		("item_code", " and pi_item.item_code = %(item_code)s"),
+		("from_date", " and pi.posting_date>=%(from_date)s"),
+		("to_date", " and pi.posting_date<=%(to_date)s")):
+			if filters.get(opts[0]):
+				conditions += opts[1]
 
 	return conditions
 	
 def get_items(filters):
 	conditions = get_conditions(filters)
-	return webnotes.conn.sql("""select pi.name, pi.posting_date, pi.credit_to, pi.company, 
+	match_conditions = webnotes.build_match_conditions("Purchase Invoice")
+	
+	return webnotes.conn.sql("""select pi_item.parent, pi.posting_date, pi.credit_to, pi.company, 
 		pi.supplier, pi.remarks, pi_item.item_code, pi_item.item_name, pi_item.item_group, 
 		pi_item.project_name, pi_item.purchase_order, pi_item.purchase_receipt, 
 		pi_item.expense_head, pi_item.qty, pi_item.rate, pi_item.amount, pi.supplier_name
 		from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` pi_item 
-		where pi.name = pi_item.parent and pi.docstatus = 1 %s 
-		order by pi.posting_date desc, pi_item.item_code desc""" % conditions, filters, as_dict=1)
+		where pi.name = pi_item.parent and pi.docstatus = 1 %s %s
+		order by pi.posting_date desc, pi_item.item_code desc""" % (conditions, match_conditions), filters, as_dict=1)
 		
 def get_aii_accounts():
-	aii_account_map = {}
-	for d in webnotes.conn.sql("select name, stock_received_but_not_billed from tabCompany",
-	 		as_dict=1):
-		aii_account_map.setdefault(d.name, d.stock_received_but_not_billed)
+	return dict(webnotes.conn.sql("select name, stock_received_but_not_billed from tabCompany"))
+	
+def get_tax_accounts(item_list, columns):
+	import json
+	item_tax = {}
+	tax_accounts = []
+	
+	tax_details = webnotes.conn.sql("""select parent, account_head, item_wise_tax_detail
+		from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice' 
+		and docstatus = 1 and ifnull(account_head, '') != '' and category in ('Total', 'Valuation and Total') 
+		and parent in (%s)""" % ', '.join(['%s']*len(item_list)), tuple([item.parent for item in item_list]))
 		
-	return aii_account_map
\ No newline at end of file
+	for parent, account_head, item_wise_tax_detail in tax_details:
+		if account_head not in tax_accounts:
+			tax_accounts.append(account_head)
+		
+		invoice = item_tax.setdefault(parent, {})
+		if item_wise_tax_detail:
+			try:
+				item_wise_tax_detail = json.loads(item_wise_tax_detail)
+				for item, tax_amount in item_wise_tax_detail.items():
+					invoice.setdefault(item, {})[account_head] = flt(tax_amount)
+				
+			except ValueError:
+				continue
+	
+	tax_accounts.sort()
+	columns += [account_head + ":Currency:80" for account_head in tax_accounts]
+	columns.append("Total:Currency:80")
+
+	return item_tax, tax_accounts
\ No newline at end of file
diff --git a/accounts/report/item_wise_sales_register/item_wise_sales_register.js b/accounts/report/item_wise_sales_register/item_wise_sales_register.js
index b9ce959..5d2dbd1 100644
--- a/accounts/report/item_wise_sales_register/item_wise_sales_register.js
+++ b/accounts/report/item_wise_sales_register/item_wise_sales_register.js
@@ -1,10 +1,10 @@
-wn.query_reports["Item-wise Sales Register"] = {
+wn.query_reports["Item-wise Sales Register"] = wn.query_reports["Sales Register"] = {
 	"filters": [
 		{
 			"fieldname":"from_date",
 			"label": "From Date",
 			"fieldtype": "Date",
-			"default": wn.defaults.get_user_default("year_start_date"),
+			"default": wn.defaults.get_default("year_start_date"),
 			"width": "80"
 		},
 		{
@@ -14,26 +14,29 @@
 			"default": get_today()
 		},
 		{
-			"fieldname": "item_code",
-			"label": "Item",
-			"fieldtype": "Link",
-			"options": "Item",
-		},
-		{
 			"fieldname":"account",
 			"label": "Account",
 			"fieldtype": "Link",
 			"options": "Account",
 			"get_query": function() {
+				var company = wn.query_report.filters_by_name.company.get_value();
 				return {
 					"query": "accounts.utils.get_account_list", 
 					"filters": {
 						"is_pl_account": "No",
 						"debit_or_credit": "Debit",
+						"company": company,
 						"master_type": "Customer"
 					}
 				}
 			}
+		},
+		{
+			"fieldname":"company",
+			"label": "Company",
+			"fieldtype": "Link",
+			"options": "Company",
+			"default": wn.defaults.get_default("company")
 		}
 	]
 }
\ No newline at end of file
diff --git a/accounts/report/item_wise_sales_register/item_wise_sales_register.py b/accounts/report/item_wise_sales_register/item_wise_sales_register.py
index 4d099e0..9df994a 100644
--- a/accounts/report/item_wise_sales_register/item_wise_sales_register.py
+++ b/accounts/report/item_wise_sales_register/item_wise_sales_register.py
@@ -16,22 +16,30 @@
 
 from __future__ import unicode_literals
 import webnotes
+from webnotes.utils import flt
 
 def execute(filters=None):
 	if not filters: filters = {}
-	
 	columns = get_columns()
+	last_col = len(columns) - 1
+	
 	item_list = get_items(filters)
+	item_tax, tax_accounts = get_tax_accounts(item_list, columns)
 	
 	data = []
 	for d in item_list:
-		data.append([d.item_code, d.item_name, d.item_group, d.name, d.posting_date, 
+		row = [d.item_code, d.item_name, d.item_group, d.parent, d.posting_date, 
 			d.customer_name, d.debit_to, d.territory, d.project_name, d.company, d.sales_order, 
-			d.delivery_note, d.income_account, d.qty, d.basic_rate, d.amount])
+			d.delivery_note, d.income_account, d.qty, d.basic_rate, d.amount]
+			
+		for tax in tax_accounts:
+			row.append(item_tax.get(d.parent, {}).get(d.item_code, {}).get(tax, 0))
+			
+		row.append(sum(row[last_col:]))
+		data.append(row)
 	
 	return columns, data
 	
-	
 def get_columns():
 	return [
 		"Item Code:Link/Item:120", "Item Name::120", "Item Group:Link/Item Group:100", 
@@ -46,21 +54,52 @@
 def get_conditions(filters):
 	conditions = ""
 	
-	if filters.get("account"): conditions += " and si.debit_to = %(account)s"
-	
-	if filters.get("item_code"): conditions += " and si_item.item_code = %(item_code)s"
-
-	if filters.get("from_date"): conditions += " and si.posting_date>=%(from_date)s"
-	if filters.get("to_date"): conditions += " and si.posting_date<=%(to_date)s"
+	for opts in (("company", " and company=%(company)s"),
+		("account", " and si.debit_to = %(account)s"),
+		("item_code", " and si_item.item_code = %(item_code)s"),
+		("from_date", " and si.posting_date>=%(from_date)s"),
+		("to_date", " and si.posting_date<=%(to_date)s")):
+			if filters.get(opts[0]):
+				conditions += opts[1]
 
 	return conditions
-	
+		
 def get_items(filters):
 	conditions = get_conditions(filters)
-	return webnotes.conn.sql("""select si.name, si.posting_date, si.debit_to, si.project_name, 
+	return webnotes.conn.sql("""select si_item.parent, si.posting_date, si.debit_to, si.project_name, 
 		si.customer, si.remarks, si.territory, si.company, si_item.item_code, si_item.item_name, 
 		si_item.item_group, si_item.sales_order, si_item.delivery_note, si_item.income_account, 
 		si_item.qty, si_item.basic_rate, si_item.amount, si.customer_name
 		from `tabSales Invoice` si, `tabSales Invoice Item` si_item 
 		where si.name = si_item.parent and si.docstatus = 1 %s 
-		order by si.posting_date desc, si_item.item_code desc""" % conditions, filters, as_dict=1)
\ No newline at end of file
+		order by si.posting_date desc, si_item.item_code desc""" % conditions, filters, as_dict=1)
+		
+def get_tax_accounts(item_list, columns):
+	import json
+	item_tax = {}
+	tax_accounts = []
+	
+	tax_details = webnotes.conn.sql("""select parent, account_head, item_wise_tax_detail
+		from `tabSales Taxes and Charges` where parenttype = 'Sales Invoice' 
+		and docstatus = 1 and ifnull(account_head, '') != ''
+		and parent in (%s)""" % ', '.join(['%s']*len(item_list)), tuple([item.parent for item in item_list]))
+		
+	for parent, account_head, item_wise_tax_detail in tax_details:
+		if account_head not in tax_accounts:
+			tax_accounts.append(account_head)
+		
+		invoice = item_tax.setdefault(parent, {})
+		if item_wise_tax_detail:
+			try:
+				item_wise_tax_detail = json.loads(item_wise_tax_detail)
+				for item, tax_amount in item_wise_tax_detail.items():
+					invoice.setdefault(item, {})[account_head] = flt(tax_amount)
+				
+			except ValueError:
+				continue
+	
+	tax_accounts.sort()
+	columns += [account_head + ":Currency:80" for account_head in tax_accounts]
+	columns.append("Total:Currency:80")
+
+	return item_tax, tax_accounts
\ No newline at end of file
diff --git a/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.js b/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.js
index d608fbd..b2b866a 100644
--- a/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.js
+++ b/accounts/report/payment_collection_with_ageing/payment_collection_with_ageing.js
@@ -36,7 +36,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		},
 	]
 }
\ No newline at end of file
diff --git a/accounts/report/payment_made_with_ageing/payment_made_with_ageing.js b/accounts/report/payment_made_with_ageing/payment_made_with_ageing.js
index 533fe61..beed7ea 100644
--- a/accounts/report/payment_made_with_ageing/payment_made_with_ageing.js
+++ b/accounts/report/payment_made_with_ageing/payment_made_with_ageing.js
@@ -34,7 +34,7 @@
 			label: "Company",
 			fieldtype: "Link",
 			options: "Company",
-			default: sys_defaults.company
+			default: wn.defaults.get_default("company")
 		},
 	]
 }
\ No newline at end of file
diff --git a/accounts/report/purchase_register/purchase_register.js b/accounts/report/purchase_register/purchase_register.js
index 21e0547..4fbd2aa 100644
--- a/accounts/report/purchase_register/purchase_register.js
+++ b/accounts/report/purchase_register/purchase_register.js
@@ -36,7 +36,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		}
 	]
 }
\ No newline at end of file
diff --git a/accounts/report/purchase_register/purchase_register.py b/accounts/report/purchase_register/purchase_register.py
index aa55a3b..12b9316 100644
--- a/accounts/report/purchase_register/purchase_register.py
+++ b/accounts/report/purchase_register/purchase_register.py
@@ -90,8 +90,8 @@
 		
 		tax_accounts = 	webnotes.conn.sql_list("""select distinct account_head 
 			from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice' 
-			and docstatus = 1 and ifnull(account_head, '') != '' and parent in (%s) 
-			order by account_head""" % 
+			and docstatus = 1 and ifnull(account_head, '') != '' and category in ('Total', 'Valuation and Total') 
+			and parent in (%s) order by account_head""" % 
 			', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]))
 			
 				
diff --git a/accounts/report/sales_register/sales_register.js b/accounts/report/sales_register/sales_register.js
index 8224619..a423f60 100644
--- a/accounts/report/sales_register/sales_register.js
+++ b/accounts/report/sales_register/sales_register.js
@@ -4,7 +4,7 @@
 			"fieldname":"from_date",
 			"label": "From Date",
 			"fieldtype": "Date",
-			"default": wn.defaults.get_user_default("year_start_date"),
+			"default": wn.defaults.get_default("year_start_date"),
 			"width": "80"
 		},
 		{
@@ -36,7 +36,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		}
 	]
 }
\ No newline at end of file
diff --git a/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.js b/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.js
index 6dc8d78..0cc802d 100644
--- a/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.js
+++ b/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.js
@@ -26,7 +26,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		}
 	]
 }
\ No newline at end of file
diff --git a/hr/report/monthly_salary_register/monthly_salary_register.js b/hr/report/monthly_salary_register/monthly_salary_register.js
index da88137..62c9d90 100644
--- a/hr/report/monthly_salary_register/monthly_salary_register.js
+++ b/hr/report/monthly_salary_register/monthly_salary_register.js
@@ -26,7 +26,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		}
 	]
 }
\ No newline at end of file
diff --git a/manufacturing/doctype/production_planning_tool/production_planning_tool.js b/manufacturing/doctype/production_planning_tool/production_planning_tool.js
index 9158748..6cd643e 100644
--- a/manufacturing/doctype/production_planning_tool/production_planning_tool.js
+++ b/manufacturing/doctype/production_planning_tool/production_planning_tool.js
@@ -15,7 +15,7 @@
 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 cur_frm.cscript.onload = function(doc, cdt, cdn) {
-	doc.company = sys_defaults.company;
+	doc.company = wn.defaults.get_default("company");
 	refresh_field("company");
 }
 
diff --git a/public/js/purchase_trends_filters.js b/public/js/purchase_trends_filters.js
index 117b9de..400fb03 100644
--- a/public/js/purchase_trends_filters.js
+++ b/public/js/purchase_trends_filters.js
@@ -33,7 +33,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		},
 	];
 }
\ No newline at end of file
diff --git a/public/js/sales_trends_filters.js b/public/js/sales_trends_filters.js
index f461d08..91f2805 100644
--- a/public/js/sales_trends_filters.js
+++ b/public/js/sales_trends_filters.js
@@ -33,7 +33,7 @@
 			"label": "Company",
 			"fieldtype": "Link",
 			"options": "Company",
-			"default": sys_defaults.company
+			"default": wn.defaults.get_default("company")
 		},	
 	];
 }
\ No newline at end of file
diff --git a/selling/doctype/opportunity/opportunity.js b/selling/doctype/opportunity/opportunity.js
index 0ac22a1..80e565a 100644
--- a/selling/doctype/opportunity/opportunity.js
+++ b/selling/doctype/opportunity/opportunity.js
@@ -31,8 +31,8 @@
 			set_multiple(cdt,cdn,{status:'Draft'});
 		if(!this.frm.doc.date) 
 			this.frm.doc.transaction_date = date.obj_to_str(new Date());
-		if(!this.frm.doc.company && sys_defaults.company) 
-			set_multiple(cdt,cdn,{company:sys_defaults.company});
+		if(!this.frm.doc.company && wn.defaults.get_default("company")) 
+			set_multiple(cdt,cdn,{company:wn.defaults.get_default("company")});
 		if(!this.frm.doc.fiscal_year && sys_defaults.fiscal_year) 
 			set_multiple(cdt,cdn,{fiscal_year:sys_defaults.fiscal_year});		
 	
diff --git a/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js b/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js
index 2e1996e..f85f699 100644
--- a/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js
+++ b/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js
@@ -30,7 +30,7 @@
 			label: "Company",
 			fieldtype: "Link",
 			options: "Company",
-			default: sys_defaults.company
+			default: wn.defaults.get_default("company")
 		},
 		{
 			fieldname:"item_group",