[Report]Cleanup of territory target variance, sales person target variance & budget variance reports
diff --git a/accounts/report/budget_variance_report/budget_variance_report.py b/accounts/report/budget_variance_report/budget_variance_report.py
index 99e303b..b4959aa 100644
--- a/accounts/report/budget_variance_report/budget_variance_report.py
+++ b/accounts/report/budget_variance_report/budget_variance_report.py
@@ -16,18 +16,21 @@
 
 from __future__ import unicode_literals
 import webnotes
-import calendar
 from webnotes import _, msgprint
 from webnotes.utils import flt
 import time
+from accounts.utils import get_fiscal_year
+from controllers.trends import get_period_date_ranges, get_period_month_ranges
 
 def execute(filters=None):
 	if not filters: filters = {}
 	
 	columns = get_columns(filters)
-	period_month_ranges = get_period_month_ranges(filters)
+	period_month_ranges = get_period_month_ranges(filters["period"], filters["fiscal_year"])
 	cam_map = get_costcenter_account_month_map(filters)
 
+	precision = webnotes.conn.get_value("Global Defaults", None, "float_precision") or 2
+
 	data = []
 
 	for cost_center, cost_center_items in cam_map.items():
@@ -39,7 +42,7 @@
 				for month in relevant_months:
 					month_data = monthwise_data.get(month, {})
 					for i, fieldname in enumerate(["target", "actual", "variance"]):
-						value = flt(month_data.get(fieldname))
+						value = flt(month_data.get(fieldname), precision)
 						period_data[i] += value
 						totals[i] += value
 				period_data[2] = period_data[0] - period_data[1]
@@ -61,7 +64,7 @@
 
 	group_months = False if filters["period"] == "Monthly" else True
 
-	for from_date, to_date in get_period_date_ranges(filters):
+	for from_date, to_date in get_period_date_ranges(filters["period"], filters["fiscal_year"]):
 		for label in ["Target (%s)", "Actual (%s)", "Variance (%s)"]:
 			if group_months:
 				columns.append(label % (from_date.strftime("%b") + " - " + to_date.strftime("%b")))				
@@ -70,41 +73,6 @@
 
 	return columns + ["Total Target::80", "Total Actual::80", "Total Variance::80"]
 
-def get_period_date_ranges(filters):
-	from dateutil.relativedelta import relativedelta
-
-	year_start_date, year_end_date = get_year_start_end_date(filters)
-
-	increment = {
-		"Monthly": 1,
-		"Quarterly": 3,
-		"Half-Yearly": 6,
-		"Yearly": 12
-	}.get(filters["period"])
-
-	period_date_ranges = []
-	for i in xrange(1, 13, increment): 
-		period_end_date = year_start_date + relativedelta(months=increment,
-			days=-1)
-		period_date_ranges.append([year_start_date, period_end_date])
-		year_start_date = period_end_date + relativedelta(days=1)
-
-	return period_date_ranges
-
-def get_period_month_ranges(filters):
-	from dateutil.relativedelta import relativedelta
-	period_month_ranges = []
-
-	for start_date, end_date in get_period_date_ranges(filters):
-		months_in_this_period = []
-		while start_date <= end_date:
-			months_in_this_period.append(start_date.strftime("%B"))
-			start_date += relativedelta(months=1)
-		period_month_ranges.append(months_in_this_period)
-
-	return period_month_ranges
-
-
 #Get cost center & target details
 def get_costcenter_target_details(filters):
 	return webnotes.conn.sql("""select cc.name, cc.distribution_id, 
@@ -122,7 +90,7 @@
 	for d in webnotes.conn.sql("""select bdd.month, bdd.percentage_allocation \
 		from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd, \
 		`tabCost Center` cc where bdd.parent=bd.name and cc.distribution_id=bd.name and \
-		bd.fiscal_year=%s""" % ('%s'), (filters.get("fiscal_year")), as_dict=1):
+		bd.fiscal_year=%s""", (filters["fiscal_year"]), as_dict=1):
 			target_details.setdefault(d.month, d)
 
 	return target_details
@@ -151,18 +119,11 @@
 			}))
 
 			tav_dict = cam_map[ccd.name][ccd.account][month]
-			tav_dict.target = ccd.budget_allocated*(tdd[month]["percentage_allocation"]/100)
+			tav_dict.target = flt(ccd.budget_allocated)*(tdd[month]["percentage_allocation"]/100)
 
 			for ad in actual_details:
 				if ad.month_name == month and ad.account == ccd.account \
 					and ad.cost_center == ccd.name:
 						tav_dict.actual += ad.debit - ad.credit
 						
-	return cam_map
-
-def get_year_start_end_date(filters):
-	return webnotes.conn.sql("""select year_start_date, 
-		subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
-			as year_end_date
-		from `tabFiscal Year`
-		where name=%s""", filters["fiscal_year"])[0]
\ No newline at end of file
+	return cam_map
\ No newline at end of file
diff --git a/selling/page/selling_home/selling_home.js b/selling/page/selling_home/selling_home.js
index 87e12db..7a0848e 100644
--- a/selling/page/selling_home/selling_home.js
+++ b/selling/page/selling_home/selling_home.js
@@ -167,12 +167,12 @@
 			},
 			{
 				"label":wn._("Territory Target Variance (Item Group-Wise)"),
-				route: "query-report/Territory Target Variance (Item Group-Wise)",
+				route: "query-report/Territory Target Variance Item Group-Wise",
 				doctype: "Sales Order"
 			},
 			{
 				"label":wn._("Sales Person Target Variance (Item Group-Wise)"),
-				route: "query-report/Sales Person Target Variance (Item Group-Wise)",
+				route: "query-report/Sales Person Target Variance Item Group-Wise",
 				doctype: "Sales Order"
 			},
 			{
diff --git "a/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.js" "b/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.js"
deleted file mode 100644
index 09f0d55..0000000
--- "a/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.js"
+++ /dev/null
@@ -1,25 +0,0 @@
-wn.query_reports["Sales Person Target Variance (Item Group-Wise)"] = {
-	"filters": [
-		{
-			fieldname: "fiscal_year",
-			label: "Fiscal Year",
-			fieldtype: "Link",
-			options: "Fiscal Year",
-			default: sys_defaults.fiscal_year
-		},
-		{
-			fieldname: "period",
-			label: "Period",
-			fieldtype: "Select",
-			options: "Monthly\nQuarterly\nHalf-Yearly\nYearly",
-			default: "Monthly"
-		},
-		{
-			fieldname: "target_on",
-			label: "Target On",
-			fieldtype: "Select",
-			options: "Quantity\nAmount",
-			default: "Quantity"
-		},
-	]
-}
\ No newline at end of file
diff --git "a/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.txt" "b/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.txt"
deleted file mode 100644
index 955cdec..0000000
--- "a/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.txt"
+++ /dev/null
@@ -1,21 +0,0 @@
-[
- {
-  "creation": "2013-06-18 12:09:40", 
-  "docstatus": 0, 
-  "modified": "2013-06-18 12:09:40", 
-  "modified_by": "Administrator", 
-  "owner": "Administrator"
- }, 
- {
-  "doctype": "Report", 
-  "is_standard": "Yes", 
-  "name": "__common__", 
-  "ref_doctype": "Sales Order", 
-  "report_name": "Sales Person Target Variance (Item Group-Wise)", 
-  "report_type": "Script Report"
- }, 
- {
-  "doctype": "Report", 
-  "name": "Sales Person Target Variance (Item Group-Wise)"
- }
-]
\ No newline at end of file
diff --git "a/selling/report/sales_person_target_variance_\050item_group_wise\051/__init__.py" b/selling/report/sales_person_target_variance_item_group_wise/__init__.py
similarity index 100%
rename from "selling/report/sales_person_target_variance_\050item_group_wise\051/__init__.py"
rename to selling/report/sales_person_target_variance_item_group_wise/__init__.py
diff --git "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.js" b/selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.js
similarity index 86%
copy from "selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.js"
copy to selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.js
index 58718a4..c7a5d66 100644
--- "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.js"
+++ b/selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.js
@@ -1,4 +1,4 @@
-wn.query_reports["Territory Target Variance (Item Group-Wise)"] = {
+wn.query_reports["Sales Person Target Variance Item Group-Wise"] = {
 	"filters": [
 		{
 			fieldname: "fiscal_year",
diff --git "a/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.py" b/selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.py
similarity index 66%
rename from "selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.py"
rename to selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.py
index 8f5931d..6e39143 100644
--- "a/selling/report/sales_person_target_variance_\050item_group_wise\051/sales_person_target_variance_\050item_group_wise\051.py"
+++ b/selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.py
@@ -16,18 +16,21 @@
 
 from __future__ import unicode_literals
 import webnotes
-import calendar
 from webnotes import _, msgprint
 from webnotes.utils import flt
 import time
+from accounts.utils import get_fiscal_year
+from controllers.trends import get_period_date_ranges, get_period_month_ranges
 
 def execute(filters=None):
 	if not filters: filters = {}
 	
 	columns = get_columns(filters)
-	period_month_ranges = get_period_month_ranges(filters)
+	period_month_ranges = get_period_month_ranges(filters["period"], filters["fiscal_year"])
 	sim_map = get_salesperson_item_month_map(filters)
 
+	precision = webnotes.conn.get_value("Global Defaults", None, "float_precision") or 2
+
 	data = []
 
 	for salesperson, salesperson_items in sim_map.items():
@@ -39,7 +42,7 @@
 				for month in relevant_months:
 					month_data = monthwise_data.get(month, {})
 					for i, fieldname in enumerate(["target", "achieved", "variance"]):
-						value = flt(month_data.get(fieldname))
+						value = flt(month_data.get(fieldname), precision)
 						period_data[i] += value
 						totals[i] += value
 				period_data[2] = period_data[0] - period_data[1]
@@ -61,7 +64,7 @@
 
 	group_months = False if filters["period"] == "Monthly" else True
 
-	for from_date, to_date in get_period_date_ranges(filters):
+	for from_date, to_date in get_period_date_ranges(filters["period"], filters["fiscal_year"]):
 		for label in ["Target (%s)", "Achieved (%s)", "Variance (%s)"]:
 			if group_months:
 				columns.append(label % (from_date.strftime("%b") + " - " + to_date.strftime("%b")))				
@@ -70,49 +73,14 @@
 
 	return columns + ["Total Target::80", "Total Achieved::80", "Total Variance::80"]
 
-def get_period_date_ranges(filters):
-	from dateutil.relativedelta import relativedelta
-
-	year_start_date, year_end_date = get_year_start_end_date(filters)
-
-	increment = {
-		"Monthly": 1,
-		"Quarterly": 3,
-		"Half-Yearly": 6,
-		"Yearly": 12
-	}.get(filters["period"])
-
-	period_date_ranges = []
-	for i in xrange(1, 13, increment): 
-		period_end_date = year_start_date + relativedelta(months=increment,
-			days=-1)
-		period_date_ranges.append([year_start_date, period_end_date])
-		year_start_date = period_end_date + relativedelta(days=1)
-
-	return period_date_ranges
-
-def get_period_month_ranges(filters):
-	from dateutil.relativedelta import relativedelta
-	period_month_ranges = []
-
-	for start_date, end_date in get_period_date_ranges(filters):
-		months_in_this_period = []
-		while start_date <= end_date:
-			months_in_this_period.append(start_date.strftime("%B"))
-			start_date += relativedelta(months=1)
-		period_month_ranges.append(months_in_this_period)
-
-	return period_month_ranges
-
-
 #Get sales person & item group details
 def get_salesperson_details(filters):
 	return webnotes.conn.sql("""select sp.name, td.item_group, td.target_qty, 
 		td.target_amount, sp.distribution_id 
 		from `tabSales Person` sp, `tabTarget Detail` td 
 		where td.parent=sp.name and td.fiscal_year=%s and 
-		ifnull(sp.distribution_id, '')!='' order by sp.name""" %
-		('%s'), (filters.get("fiscal_year")), as_dict=1)
+		ifnull(sp.distribution_id, '')!='' order by sp.name""", 
+		(filters["fiscal_year"]), as_dict=1)
 
 #Get target distribution details of item group
 def get_target_distribution_details(filters):
@@ -121,14 +89,14 @@
 	for d in webnotes.conn.sql("""select bdd.month, bdd.percentage_allocation \
 		from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd, \
 		`tabTerritory` t where bdd.parent=bd.name and t.distribution_id=bd.name and \
-		bd.fiscal_year=%s  """ % ('%s'), (filters.get("fiscal_year")), as_dict=1):
+		bd.fiscal_year=%s""", (filters["fiscal_year"]), as_dict=1):
 			target_details.setdefault(d.month, d)
 
 	return target_details
 
 #Get achieved details from sales order
 def get_achieved_details(filters):
-	start_date, end_date = get_year_start_end_date(filters)
+	start_date, end_date = get_fiscal_year(filters)[1:]
 	
 	return webnotes.conn.sql("""select soi.item_code, soi.qty, soi.amount, so.transaction_date, 
 		st.sales_person, MONTHNAME(so.transaction_date) as month_name 
@@ -156,28 +124,18 @@
 
 			for ad in achieved_details:
 				if (filters["target_on"] == "Quantity"):
-					tav_dict.target = sd.target_qty*(tdd[month]["percentage_allocation"]/100)
-					if ad.month_name == month and ''.join(get_item_group(ad.item_code)) == sd.item_group \
+					tav_dict.target = flt(sd.target_qty)*(tdd[month]["percentage_allocation"]/100)
+					if ad.month_name == month and get_item_group(ad.item_code) == sd.item_group \
 						and ad.sales_person == sd.name:
 							tav_dict.achieved += ad.qty
 
 				if (filters["target_on"] == "Amount"):
-					tav_dict.target = sd.target_amount*(tdd[month]["percentage_allocation"]/100)
-					if ad.month_name == month and ''.join(get_item_group(ad.item_code)) == sd.item_group \
+					tav_dict.target = flt(sd.target_amount)*(tdd[month]["percentage_allocation"]/100)
+					if ad.month_name == month and get_item_group(ad.item_code) == sd.item_group \
 						and ad.sales_person == sd.name:
 							tav_dict.achieved += ad.amount
 
 	return sim_map
 
-def get_year_start_end_date(filters):
-	return webnotes.conn.sql("""select year_start_date, 
-		subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
-			as year_end_date
-		from `tabFiscal Year`
-		where name=%s""", filters["fiscal_year"])[0]
-
 def get_item_group(item_name):
-	"""Get Item Group of an item"""
-
-	return webnotes.conn.sql_list("select item_group from `tabItem` where name=%s""" %
-		('%s'), (item_name))
\ No newline at end of file
+	return webnotes.conn.get_value("Item", item_name, item_group)
\ No newline at end of file
diff --git a/selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.txt b/selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.txt
new file mode 100644
index 0000000..e587c2c
--- /dev/null
+++ b/selling/report/sales_person_target_variance_item_group_wise/sales_person_target_variance_item_group_wise.txt
@@ -0,0 +1,21 @@
+[
+ {
+  "creation": "2013-06-21 12:14:15", 
+  "docstatus": 0, 
+  "modified": "2013-06-21 12:14:15", 
+  "modified_by": "Administrator", 
+  "owner": "Administrator"
+ }, 
+ {
+  "doctype": "Report", 
+  "is_standard": "Yes", 
+  "name": "__common__", 
+  "ref_doctype": "Sales Order", 
+  "report_name": "Sales Person Target Variance Item Group-Wise", 
+  "report_type": "Script Report"
+ }, 
+ {
+  "doctype": "Report", 
+  "name": "Sales Person Target Variance Item Group-Wise"
+ }
+]
\ No newline at end of file
diff --git "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.txt" "b/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.txt"
deleted file mode 100644
index 7fff64a..0000000
--- "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.txt"
+++ /dev/null
@@ -1,21 +0,0 @@
-[
- {
-  "creation": "2013-06-07 15:13:13", 
-  "docstatus": 0, 
-  "modified": "2013-06-07 15:13:13", 
-  "modified_by": "Administrator", 
-  "owner": "Administrator"
- }, 
- {
-  "doctype": "Report", 
-  "is_standard": "Yes", 
-  "name": "__common__", 
-  "ref_doctype": "Sales Order", 
-  "report_name": "Territory Target Variance (Item Group-Wise)", 
-  "report_type": "Script Report"
- }, 
- {
-  "doctype": "Report", 
-  "name": "Territory Target Variance (Item Group-Wise)"
- }
-]
\ No newline at end of file
diff --git "a/selling/report/territory_target_variance_\050item_group_wise\051/__init__.py" b/selling/report/territory_target_variance_item_group_wise/__init__.py
similarity index 100%
rename from "selling/report/territory_target_variance_\050item_group_wise\051/__init__.py"
rename to selling/report/territory_target_variance_item_group_wise/__init__.py
diff --git "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.js" b/selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.js
similarity index 86%
rename from "selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.js"
rename to selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.js
index 58718a4..146b17d 100644
--- "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.js"
+++ b/selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.js
@@ -1,4 +1,4 @@
-wn.query_reports["Territory Target Variance (Item Group-Wise)"] = {
+wn.query_reports["Territory Target Variance Item Group-Wise"] = {
 	"filters": [
 		{
 			fieldname: "fiscal_year",
diff --git "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.py" b/selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.py
similarity index 66%
rename from "selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.py"
rename to selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.py
index 079f8e8..e7ddc6e 100644
--- "a/selling/report/territory_target_variance_\050item_group_wise\051/territory_target_variance_\050item_group_wise\051.py"
+++ b/selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.py
@@ -16,18 +16,21 @@
 
 from __future__ import unicode_literals
 import webnotes
-import calendar
 from webnotes import _, msgprint
 from webnotes.utils import flt
 import time
+from accounts.utils import get_fiscal_year
+from controllers.trends import get_period_date_ranges, get_period_month_ranges
 
 def execute(filters=None):
 	if not filters: filters = {}
 	
 	columns = get_columns(filters)
-	period_month_ranges = get_period_month_ranges(filters)
+	period_month_ranges = get_period_month_ranges(filters["period"], filters["fiscal_year"])
 	tim_map = get_territory_item_month_map(filters)
 
+	precision = webnotes.conn.get_value("Global Defaults", None, "float_precision") or 2
+
 	data = []
 
 	for territory, territory_items in tim_map.items():
@@ -39,7 +42,7 @@
 				for month in relevant_months:
 					month_data = monthwise_data.get(month, {})
 					for i, fieldname in enumerate(["target", "achieved", "variance"]):
-						value = flt(month_data.get(fieldname))
+						value = flt(month_data.get(fieldname), precision)
 						period_data[i] += value
 						totals[i] += value
 				period_data[2] = period_data[0] - period_data[1]
@@ -61,7 +64,7 @@
 
 	group_months = False if filters["period"] == "Monthly" else True
 
-	for from_date, to_date in get_period_date_ranges(filters):
+	for from_date, to_date in get_period_date_ranges(filters["period"], filters["fiscal_year"]):
 		for label in ["Target (%s)", "Achieved (%s)", "Variance (%s)"]:
 			if group_months:
 				columns.append(label % (from_date.strftime("%b") + " - " + to_date.strftime("%b")))				
@@ -70,49 +73,14 @@
 
 	return columns + ["Total Target::80", "Total Achieved::80", "Total Variance::80"]
 
-def get_period_date_ranges(filters):
-	from dateutil.relativedelta import relativedelta
-
-	year_start_date, year_end_date = get_year_start_end_date(filters)
-
-	increment = {
-		"Monthly": 1,
-		"Quarterly": 3,
-		"Half-Yearly": 6,
-		"Yearly": 12
-	}.get(filters["period"])
-
-	period_date_ranges = []
-	for i in xrange(1, 13, increment): 
-		period_end_date = year_start_date + relativedelta(months=increment,
-			days=-1)
-		period_date_ranges.append([year_start_date, period_end_date])
-		year_start_date = period_end_date + relativedelta(days=1)
-
-	return period_date_ranges
-
-def get_period_month_ranges(filters):
-	from dateutil.relativedelta import relativedelta
-	period_month_ranges = []
-
-	for start_date, end_date in get_period_date_ranges(filters):
-		months_in_this_period = []
-		while start_date <= end_date:
-			months_in_this_period.append(start_date.strftime("%B"))
-			start_date += relativedelta(months=1)
-		period_month_ranges.append(months_in_this_period)
-
-	return period_month_ranges
-
-
 #Get territory & item group details
 def get_territory_details(filters):
 	return webnotes.conn.sql("""select t.name, td.item_group, td.target_qty, 
 		td.target_amount, t.distribution_id 
 		from `tabTerritory` t, `tabTarget Detail` td 
 		where td.parent=t.name and td.fiscal_year=%s and 
-		ifnull(t.distribution_id, '')!='' order by t.name""" %
-		('%s'), (filters.get("fiscal_year")), as_dict=1)
+		ifnull(t.distribution_id, '')!='' order by t.name""", 
+		(filters["fiscal_year"]), as_dict=1)
 
 #Get target distribution details of item group
 def get_target_distribution_details(filters):
@@ -121,14 +89,14 @@
 	for d in webnotes.conn.sql("""select bdd.month, bdd.percentage_allocation \
 		from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd, \
 		`tabTerritory` t where bdd.parent=bd.name and t.distribution_id=bd.name and \
-		bd.fiscal_year=%s""" % ('%s'), (filters.get("fiscal_year")), as_dict=1):
+		bd.fiscal_year=%s""", (filters["fiscal_year"]), as_dict=1):
 			target_details.setdefault(d.month, d)
 
 	return target_details
 
 #Get achieved details from sales order
 def get_achieved_details(filters):
-	start_date, end_date = get_year_start_end_date(filters)
+	start_date, end_date = get_fiscal_year(filters)[1:]
 
 	return webnotes.conn.sql("""select soi.item_code, soi.qty, soi.amount, so.transaction_date, 
 		so.territory, MONTHNAME(so.transaction_date) as month_name 
@@ -155,28 +123,18 @@
 
 			for ad in achieved_details:
 				if (filters["target_on"] == "Quantity"):
-					tav_dict.target = td.target_qty*(tdd[month]["percentage_allocation"]/100)
-					if ad.month_name == month and ''.join(get_item_group(ad.item_code)) == td.item_group \
+					tav_dict.target = flt(td.target_qty)*(tdd[month]["percentage_allocation"]/100)
+					if ad.month_name == month and get_item_group(ad.item_code) == td.item_group \
 						and ad.territory == td.name:
 							tav_dict.achieved += ad.qty
 
 				if (filters["target_on"] == "Amount"):
-					tav_dict.target = td.target_amount*(tdd[month]["percentage_allocation"]/100)
-					if ad.month_name == month and ''.join(get_item_group(ad.item_code)) == td.item_group \
+					tav_dict.target = flt(td.target_amount)*(tdd[month]["percentage_allocation"]/100)
+					if ad.month_name == month and get_item_group(ad.item_code) == td.item_group \
 						and ad.territory == td.name:
 							tav_dict.achieved += ad.amount
 
 	return tim_map
 
-def get_year_start_end_date(filters):
-	return webnotes.conn.sql("""select year_start_date, 
-		subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
-			as year_end_date
-		from `tabFiscal Year`
-		where name=%s""", filters["fiscal_year"])[0]
-
 def get_item_group(item_name):
-	"""Get Item Group of an item"""
-
-	return webnotes.conn.sql_list("select item_group from `tabItem` where name=%s""" %
-		('%s'), (item_name))
\ No newline at end of file
+	return webnotes.conn.get_value("Item", item_name, item_group)
\ No newline at end of file
diff --git a/selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.txt b/selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.txt
new file mode 100644
index 0000000..6e16b64
--- /dev/null
+++ b/selling/report/territory_target_variance_item_group_wise/territory_target_variance_item_group_wise.txt
@@ -0,0 +1,21 @@
+[
+ {
+  "creation": "2013-06-21 12:15:00", 
+  "docstatus": 0, 
+  "modified": "2013-06-21 12:15:00", 
+  "modified_by": "Administrator", 
+  "owner": "Administrator"
+ }, 
+ {
+  "doctype": "Report", 
+  "is_standard": "Yes", 
+  "name": "__common__", 
+  "ref_doctype": "Sales Order", 
+  "report_name": "Territory Target Variance Item Group-Wise", 
+  "report_type": "Script Report"
+ }, 
+ {
+  "doctype": "Report", 
+  "name": "Territory Target Variance Item Group-Wise"
+ }
+]
\ No newline at end of file
diff --git a/stock/report/item_prices/item_prices.py b/stock/report/item_prices/item_prices.py
index 86ae085..7a3877b 100644
--- a/stock/report/item_prices/item_prices.py
+++ b/stock/report/item_prices/item_prices.py
@@ -24,16 +24,22 @@
 	columns = get_columns(filters)
 	item_map = get_item_details()
 	pl = get_price_list()
+	last_purchase_rate = get_last_purchase_rate()
 	bom_rate = get_item_bom_rate()
 	val_rate_map = get_valuation_rate()
+
+	precision = webnotes.conn.get_value("Global Defaults", None, "float_precision") or 2
 	
 	data = []
 	for item in sorted(item_map):
 		data.append([item, item_map[item]["item_name"], 
 			item_map[item]["description"], item_map[item]["stock_uom"], 
-			flt(item_map[item]["last_purchase_rate"]), val_rate_map.get(item, 0), 
-			pl.get(item, {}).get("selling"), pl.get(item, {}).get("buying"), 
-			bom_rate.get(item, 0), flt(item_map[item]["standard_rate"])
+			flt(last_purchase_rate.get(item, 0), precision), 
+			flt(val_rate_map.get(item, 0), precision), 
+			pl.get(item, {}).get("selling"), 
+			pl.get(item, {}).get("buying"), 
+			flt(bom_rate.get(item, 0), precision), 
+			flt(item_map[item]["standard_rate"])
 		])
 	
 	return columns, data
@@ -53,7 +59,7 @@
 	item_map = {}
 	
 	for i in webnotes.conn.sql("select name, item_name, description, \
-		stock_uom, standard_rate, last_purchase_rate from tabItem \
+		stock_uom, standard_rate from tabItem \
 		order by item_code", as_dict=1):
 			item_map.setdefault(i.name, i)
 
@@ -84,24 +90,60 @@
 	
 	return item_rate_map
 
+def get_last_purchase_rate():
+
+	item_last_purchase_rate_map = {}
+
+	query = """select * from (select 
+					result.item_code,
+					result.purchase_rate
+					from (
+						(select 
+							po_item.item_code,
+							po_item.item_name,
+							po.transaction_date as posting_date,
+							po_item.purchase_ref_rate, 
+							po_item.discount_rate, 
+							po_item.purchase_rate
+						from `tabPurchase Order` po, `tabPurchase Order Item` po_item
+						where po.name = po_item.parent and po.docstatus = 1)
+						union
+						(select 
+							pr_item.item_code,
+							pr_item.item_name,
+							pr.posting_date,
+							pr_item.purchase_ref_rate,
+							pr_item.discount_rate,
+							pr_item.purchase_rate
+						from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pr_item
+						where pr.name = pr_item.parent and pr.docstatus = 1)
+				) result
+				order by result.item_code asc, result.posting_date desc) result_wrapper
+				group by item_code"""
+
+	for d in webnotes.conn.sql(query, as_dict=1):
+		item_last_purchase_rate_map.setdefault(d.item_code, d.purchase_rate)
+
+	return item_last_purchase_rate_map
+
 def get_item_bom_rate():
 	"""Get BOM rate of an item from BOM"""
 
-	bom_map = {}
+	item_bom_map = {}
 	
 	for b in webnotes.conn.sql("""select item, (total_cost/quantity) as bom_rate 
 		from `tabBOM` where is_active=1 and is_default=1""", as_dict=1):
-			bom_map.setdefault(b.item, flt(b.bom_rate))
+			item_bom_map.setdefault(b.item, flt(b.bom_rate))
 
-	return bom_map
+	return item_bom_map
 
 def get_valuation_rate():
 	"""Get an average valuation rate of an item from all warehouses"""
 
-	val_rate_map = {}
+	item_val_rate_map = {}
 	
 	for d in webnotes.conn.sql("""select item_code, avg(valuation_rate) as val_rate
 		from tabBin group by item_code""", as_dict=1):
-			val_rate_map.setdefault(d.item_code, d.val_rate)
+			item_val_rate_map.setdefault(d.item_code, flt(d.val_rate))
 
-	return val_rate_map
\ No newline at end of file
+	return item_val_rate_map
\ No newline at end of file