Merge branch 'master' of github.com:webnotes/erpnext
diff --git a/accounts/doctype/fiscal_year/fiscal_year.js b/accounts/doctype/fiscal_year/fiscal_year.js
index 7923a02..feae286 100644
--- a/accounts/doctype/fiscal_year/fiscal_year.js
+++ b/accounts/doctype/fiscal_year/fiscal_year.js
@@ -1,18 +1,39 @@
 // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
 // License: GNU General Public License v3. See license.txt
 
-cur_frm.cscript.refresh = function(doc, dt, dn) {
-	cur_frm.toggle_enable('year_start_date', doc.__islocal)
+$.extend(cur_frm.cscript, {
+	refresh: function (doc, dt, dn) {
+		var me = this;
+		this.frm.toggle_enable('year_start_date', doc.__islocal)
+		this.frm.toggle_enable('year_end_date', doc.__islocal)
 	
-	if (!doc.__islocal && (doc.name != sys_defaults.fiscal_year)) {
-		cur_frm.add_custom_button(wn._("Set as Default"), cur_frm.cscript.set_as_default);
-		cur_frm.set_intro(wn._("To set this Fiscal Year as Deafult, click on 'Set as Default'"));
-	} else cur_frm.set_intro("");
-}
+		if (!doc.__islocal && (doc.name != sys_defaults.fiscal_year)) {
+			this.frm.add_custom_button(wn._("Set as Default"), this.frm.cscript.set_as_default);
+			this.frm.set_intro(wn._("To set this Fiscal Year as Default, click on 'Set as Default'"));
+		} else this.frm.set_intro("");
 
-cur_frm.cscript.set_as_default = function() {
-	return wn.call({
-		doc: cur_frm.doc,
-		method: "set_as_default"
-	});
-}
\ No newline at end of file
+		if (doc.__islocal && this.frm.doc.year_start_date)
+			this.frm.script_manager.trigger("year_start_date", dt, dn);
+	},
+	set_as_default: function() {
+		return wn.call({
+			doc: cur_frm.doc,
+			method: "set_as_default"
+		});
+	},
+	year_start_date: function(doc, dt, dn) {
+		var me = this;
+
+		wn.call({
+			method: 'controllers.trends.get_period_date_ranges',
+			args: {
+				period: "Yearly",
+				year_start_date: this.frm.doc.year_start_date
+			},
+			callback: function(r) {
+				if (!r.exc)
+					me.frm.set_value("year_end_date", r.message[0][1])
+			}
+		});
+	},
+});
\ No newline at end of file
diff --git a/accounts/doctype/fiscal_year/fiscal_year.py b/accounts/doctype/fiscal_year/fiscal_year.py
index 0e5ebe5..1cc659a 100644
--- a/accounts/doctype/fiscal_year/fiscal_year.py
+++ b/accounts/doctype/fiscal_year/fiscal_year.py
@@ -17,4 +17,24 @@
 		webnotes.clear_cache()
 		
 		msgprint(self.doc.name + _(""" is now the default Fiscal Year. \
-			Please refresh your browser for the change to take effect."""))
\ No newline at end of file
+			Please refresh your browser for the change to take effect."""))
+
+	def on_update(self):
+		from webnotes.utils import getdate
+
+		# validate year start date and year end date
+		if getdate(self.doc.year_start_date) > getdate(self.doc.year_end_date):
+			webnotes.throw(_("Year Start Date should not be greater than Year End Date"))
+
+		if (getdate(self.doc.year_end_date) - getdate(self.doc.year_start_date)).days > 366:
+			webnotes.throw([getdate(self.doc.year_end_date), getdate(self.doc.year_start_date)])
+			webnotes.throw((getdate(self.doc.year_end_date) - getdate(self.doc.year_start_date)).days)
+			webnotes.throw(_("Year Start Date and Year End Date are not within Fiscal Year."))
+
+		year_start_end_dates = webnotes.conn.sql("""select name, year_start_date, year_end_date 
+			from `tabFiscal Year` where name!=%s""", (self.doc.name))
+
+		for fiscal_year, ysd, yed in year_start_end_dates:
+			if getdate(self.doc.year_start_date) == ysd and getdate(self.doc.year_end_date) == yed:
+				webnotes.throw(_("Year Start Date and Year End Date are already \
+					set in Fiscal Year: ") + fiscal_year)
\ No newline at end of file
diff --git a/accounts/doctype/fiscal_year/fiscal_year.txt b/accounts/doctype/fiscal_year/fiscal_year.txt
index 6d64fcd..1cf98fb 100644
--- a/accounts/doctype/fiscal_year/fiscal_year.txt
+++ b/accounts/doctype/fiscal_year/fiscal_year.txt
@@ -2,7 +2,7 @@
  {
   "creation": "2013-01-22 16:50:25", 
   "docstatus": 0, 
-  "modified": "2013-07-23 11:59:11", 
+  "modified": "2013-11-25 11:40:02", 
   "modified_by": "Administrator", 
   "owner": "Administrator"
  }, 
@@ -57,6 +57,14 @@
   "reqd": 1
  }, 
  {
+  "doctype": "DocField", 
+  "fieldname": "year_end_date", 
+  "fieldtype": "Date", 
+  "label": "Year End Date", 
+  "no_copy": 1, 
+  "reqd": 1
+ }, 
+ {
   "default": "No", 
   "description": "Entries are not allowed against this Fiscal Year if the year is closed.", 
   "doctype": "DocField", 
diff --git a/accounts/doctype/fiscal_year/test_fiscal_year.py b/accounts/doctype/fiscal_year/test_fiscal_year.py
index 4ea8253..cd9b1f4 100644
--- a/accounts/doctype/fiscal_year/test_fiscal_year.py
+++ b/accounts/doctype/fiscal_year/test_fiscal_year.py
@@ -7,26 +7,31 @@
 	[{
 		"doctype": "Fiscal Year", 
 		"year": "_Test Fiscal Year 2012", 
-		"year_start_date": "2012-01-01"
+		"year_start_date": "2012-01-01",
+		"year_end_date": "2012-12-31"
 	}],
 	[{
 		"doctype": "Fiscal Year", 
 		"year": "_Test Fiscal Year 2013", 
-		"year_start_date": "2013-01-01"
+		"year_start_date": "2013-01-01",
+		"year_end_date": "2013-12-31"
 	}],
 	[{
 		"doctype": "Fiscal Year",
 		"year": "_Test Fiscal Year 2014", 
-		"year_start_date": "2014-01-01"
+		"year_start_date": "2014-01-01",
+		"year_end_date": "2014-12-31"
 	}],
 	[{
 		"doctype": "Fiscal Year",
 		"year": "_Test Fiscal Year 2015", 
-		"year_start_date": "2015-01-01"
+		"year_start_date": "2015-01-01",
+		"year_end_date": "2015-12-31"
 	}],
 	[{
 		"doctype": "Fiscal Year",
 		"year": "_Test Fiscal Year 2016", 
-		"year_start_date": "2016-01-01"
+		"year_start_date": "2016-01-01",
+		"year_end_date": "2016-12-31"
 	}],
 ]
\ No newline at end of file
diff --git a/accounts/doctype/mis_control/mis_control.py b/accounts/doctype/mis_control/mis_control.py
index 1068cf3..3637d44 100644
--- a/accounts/doctype/mis_control/mis_control.py
+++ b/accounts/doctype/mis_control/mis_control.py
@@ -254,7 +254,6 @@
 			for i in range(4):
 				pn = 'Q'+str(i+1)
 				self.period_list.append(pn)
-			
 				self.period_start_date[pn] = get_first_day(ysd,0,i*3)
 				self.period_end_date[pn] = get_last_day(get_first_day(ysd,0,((i+1)*3)-1))	
 
diff --git a/accounts/doctype/period_closing_voucher/period_closing_voucher.py b/accounts/doctype/period_closing_voucher/period_closing_voucher.py
index 69061bf..5d7fc1e 100644
--- a/accounts/doctype/period_closing_voucher/period_closing_voucher.py
+++ b/accounts/doctype/period_closing_voucher/period_closing_voucher.py
@@ -34,7 +34,7 @@
 
 	def validate_posting_date(self):
 		from accounts.utils import get_fiscal_year
-		self.year_start_date = get_fiscal_year(self.doc.posting_date)[1]
+		self.year_start_date = get_fiscal_year(self.doc.posting_date, self.doc.fiscal_year)[1]
 
 		pce = webnotes.conn.sql("""select name from `tabPeriod Closing Voucher`
 			where posting_date > %s and fiscal_year = %s and docstatus = 1""", 
diff --git a/accounts/utils.py b/accounts/utils.py
index 3ca1a8a..7f8f0e6 100644
--- a/accounts/utils.py
+++ b/accounts/utils.py
@@ -24,14 +24,10 @@
 	if fiscal_year:
 		cond = "name = '%s'" % fiscal_year
 	else:
-		cond = "'%s' >= year_start_date and '%s' < adddate(year_start_date, interval 1 year)" % \
+		cond = "'%s' >= year_start_date and '%s' <= year_end_date" % \
 			(date, date)
-	fy = webnotes.conn.sql("""select name, year_start_date, 
-		subdate(adddate(year_start_date, interval 1 year), interval 1 day) 
-			as year_end_date
-		from `tabFiscal Year`
-		where %s
-		order by year_start_date desc""" % cond)
+	fy = webnotes.conn.sql("""select name, year_start_date, year_end_date
+		from `tabFiscal Year` where %s order by year_start_date desc""" % cond)
 	
 	if not fy:
 		error_msg = """%s %s not in any Fiscal Year""" % (label, formatdate(date))
diff --git a/controllers/trends.py b/controllers/trends.py
index 7d96a4e..7559b1f 100644
--- a/controllers/trends.py
+++ b/controllers/trends.py
@@ -151,24 +151,32 @@
 				""" % {"trans_date": trans_date, "sd": bet_dates[0],"ed": bet_dates[1]}
 	return query_details
 
-def get_period_date_ranges(period, fiscal_year):
-  from dateutil.relativedelta import relativedelta
+@webnotes.whitelist(allow_guest=True)
+def get_period_date_ranges(period, fiscal_year=None, year_start_date=None):
+	from dateutil.relativedelta import relativedelta
 
-  year_start_date = webnotes.conn.get_value("Fiscal Year", fiscal_year, "year_start_date")
-  increment = {
-    "Monthly": 1,
-    "Quarterly": 3,
-    "Half-Yearly": 6,
-    "Yearly": 12
-  }.get(period)
+	if not year_start_date:
+		year_start_date, year_end_date = webnotes.conn.get_value("Fiscal Year", 
+			fiscal_year, ["year_start_date", "year_end_date"])
 
-  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)
+	increment = {
+		"Monthly": 1,
+		"Quarterly": 3,
+		"Half-Yearly": 6,
+		"Yearly": 12
+	}.get(period)
 
-  return period_date_ranges
+	period_date_ranges = []
+	for i in xrange(1, 13, increment):
+		period_end_date = getdate(year_start_date) + relativedelta(months=increment, days=-1)
+		if period_end_date > getdate(year_end_date):
+			period_end_date = year_end_date
+		period_date_ranges.append([year_start_date, period_end_date])
+		year_start_date = period_end_date + relativedelta(days=1)
+		if period_end_date == year_end_date:
+			break
+
+	return period_date_ranges
 
 def get_period_month_ranges(period, fiscal_year):
 	from dateutil.relativedelta import relativedelta
diff --git a/hr/doctype/holiday_list/holiday_list.py b/hr/doctype/holiday_list/holiday_list.py
index 441f1dc..1045077 100644
--- a/hr/doctype/holiday_list/holiday_list.py
+++ b/hr/doctype/holiday_list/holiday_list.py
@@ -45,11 +45,8 @@
 			raise Exception
 
 	def get_fy_start_end_dates(self):
-		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""", (self.doc.fiscal_year,))[0]
+		return webnotes.conn.sql("""select year_start_date, year_end_date
+			from `tabFiscal Year` where name=%s""", (self.doc.fiscal_year,))[0]
 
 	def get_weekly_off_date_list(self, year_start_date, year_end_date):
 		from webnotes.utils import getdate
diff --git a/hr/doctype/salary_manager/salary_manager.py b/hr/doctype/salary_manager/salary_manager.py
index 35576f3..9eab5f3 100644
--- a/hr/doctype/salary_manager/salary_manager.py
+++ b/hr/doctype/salary_manager/salary_manager.py
@@ -59,7 +59,6 @@
 		return cond
 		
 		
-		
 	def check_mandatory(self):
 		for f in ['company', 'month', 'fiscal_year']:
 			if not self.doc.fields[f]:
@@ -84,8 +83,6 @@
 				'month_days': month_days
 			}
 
-		
-		
 	def create_sal_slip(self):
 		"""
 			Creates salary slip for selected employees if already not created
diff --git a/patches/1311/p04_update_year_end_date_of_fiscal_year.py b/patches/1311/p04_update_year_end_date_of_fiscal_year.py
new file mode 100644
index 0000000..0b0399a
--- /dev/null
+++ b/patches/1311/p04_update_year_end_date_of_fiscal_year.py
@@ -0,0 +1,11 @@
+# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import webnotes
+
+def execute():
+	webnotes.reload_doc("accounts", "doctype", "fiscal_year")
+
+	webnotes.conn.sql("""update `tabFiscal Year` set year_end_date = 
+		subdate(adddate(year_start_date, interval 1 year), interval 1 day)""")
\ No newline at end of file
diff --git a/patches/patch_list.py b/patches/patch_list.py
index ad7bd4f..d09cec1 100644
--- a/patches/patch_list.py
+++ b/patches/patch_list.py
@@ -249,7 +249,8 @@
 	"execute:webnotes.reload_doc('website', 'doctype', 'website_sitemap_config') #2013-11-20",
 	"execute:webnotes.reload_doc('website', 'doctype', 'website_sitemap') #2013-11-20",
 	"execute:webnotes.bean('Style Settings').save() #2013-11-20",
-	"execute:webnotes.get_module('website.doctype.website_sitemap_config.website_sitemap_config').rebuild_website_sitemap_config()",
+    "execute:webnotes.get_module('website.doctype.website_sitemap_config.website_sitemap_config').rebuild_website_sitemap_config()",
+    "patches.1311.p04_update_year_end_date_of_fiscal_year",
 	"patches.1311.p04_update_comments",
 	"patches.1311.p05_website_brand_html",
 ]
\ No newline at end of file
diff --git a/setup/doctype/currency_exchange/test_currency_exchange.py b/setup/doctype/currency_exchange/test_currency_exchange.py
index 0f8caed..f8260be 100644
--- a/setup/doctype/currency_exchange/test_currency_exchange.py
+++ b/setup/doctype/currency_exchange/test_currency_exchange.py
@@ -13,5 +13,11 @@
 		"from_currency": "USD",
 		"to_currency": "EUR",
 		"exchange_rate": 0.773
-	}]
+	}],
+	[{
+		"doctype": "Currency Exchange",
+		"from_currency": "INR",
+		"to_currency": "USD",
+		"exchange_rate": 0.0167
+	}],
 ]
\ 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 6d535bf..9c5ef86 100644
--- a/setup/doctype/global_defaults/global_defaults.py
+++ b/setup/doctype/global_defaults/global_defaults.py
@@ -35,15 +35,15 @@
 			webnotes.conn.set_default(key, self.doc.fields.get(keydict[key], ''))
 			
 		# update year start date and year end date from fiscal_year
-		ysd = webnotes.conn.sql("""select year_start_date from `tabFiscal Year` 
-			where name=%s""", self.doc.current_fiscal_year)
-			
-		ysd = ysd and ysd[0][0] or ''
-		from webnotes.utils import get_first_day, get_last_day
-		if ysd:
+		year_start_end_date = webnotes.conn.sql("""select year_start_date, year_end_date 
+			from `tabFiscal Year` where name=%s""", self.doc.current_fiscal_year)
+
+		ysd = year_start_end_date[0][0] or ''
+		yed = year_start_end_date[0][1] or ''
+
+		if ysd and yed:
 			webnotes.conn.set_default('year_start_date', ysd.strftime('%Y-%m-%d'))
-			webnotes.conn.set_default('year_end_date', \
-				get_last_day(get_first_day(ysd,0,11)).strftime('%Y-%m-%d'))
+			webnotes.conn.set_default('year_end_date', yed.strftime('%Y-%m-%d'))
 		
 		# enable default currency
 		if self.doc.default_currency:
diff --git a/setup/page/setup_wizard/setup_wizard.js b/setup/page/setup_wizard/setup_wizard.js
index a706194..9f775e0 100644
--- a/setup/page/setup_wizard/setup_wizard.js
+++ b/setup/page/setup_wizard/setup_wizard.js
@@ -88,9 +88,10 @@
 						placeholder: 'e.g. "My Company LLC"'},
 					{fieldname:'company_abbr', label: wn._('Company Abbreviation'), fieldtype:'Data',
 						placeholder:'e.g. "MC"',reqd:1},
-					{fieldname:'fy_start', label:'Financial Year Start Date', fieldtype:'Select',
-						description:'Your financial year begins on', reqd:1,
-						options: ['', '1st Jan', '1st Apr', '1st Jul', '1st Oct'] },
+					{fieldname:'fy_start_date', label:'Financial Year Start Date', fieldtype:'Date',
+						description:'Your financial year begins on', reqd:1},
+					{fieldname:'fy_end_date', label:'Financial Year End Date', fieldtype:'Date',
+						description:'Your financial year ends on', reqd:1},
 					{fieldname:'company_tagline', label: wn._('What does it do?'), fieldtype:'Data',
 						placeholder:'e.g. "Build tools for builders"', reqd:1},
 				],
diff --git a/setup/page/setup_wizard/setup_wizard.py b/setup/page/setup_wizard/setup_wizard.py
index bdf95de..bf14905 100644
--- a/setup/page/setup_wizard/setup_wizard.py
+++ b/setup/page/setup_wizard/setup_wizard.py
@@ -72,18 +72,12 @@
 	add_all_roles_to(args.get("name"))
 	
 def create_fiscal_year_and_company(args):
-	curr_fiscal_year, fy_start_date, fy_abbr = get_fy_details(args.get('fy_start'), True)
+	curr_fiscal_year = get_fy_details(args.get('fy_start_date'), args.get('fy_end_date'))
 	webnotes.bean([{
 		"doctype":"Fiscal Year",
 		'year': curr_fiscal_year,
-		'year_start_date': fy_start_date
-	}]).insert()
-
-	curr_fiscal_year, fy_start_date, fy_abbr = get_fy_details(args.get('fy_start'))
-	webnotes.bean([{
-		"doctype":"Fiscal Year",
-		'year': curr_fiscal_year,
-		'year_start_date': fy_start_date,
+		'year_start_date': args.get('fy_start_date'),
+		'year_end_date': args.get('fy_end_date'),
 	}]).insert()
 
 	
@@ -196,25 +190,13 @@
 		
 			edigest.insert()
 		
-def get_fy_details(fy_start, last_year=False):
-	st = {'1st Jan':'01-01','1st Apr':'04-01','1st Jul':'07-01', '1st Oct': '10-01'}
-	if cint(getdate(nowdate()).month) < cint((st[fy_start].split('-'))[0]):
-		curr_year = getdate(nowdate()).year - 1
+def get_fy_details(fy_start_date, fy_end_date):
+	start_year = getdate(fy_start_date).year
+	if start_year == getdate(fy_end_date).year:
+		fy = cstr(start_year)
 	else:
-		curr_year = getdate(nowdate()).year
-	
-	if last_year:
-		curr_year = curr_year - 1
-	
-	stdt = cstr(curr_year)+'-'+cstr(st[fy_start])
-
-	if(fy_start == '1st Jan'):
-		fy = cstr(curr_year)
-		abbr = cstr(fy)[-2:]
-	else:
-		fy = cstr(curr_year) + '-' + cstr(curr_year+1)
-		abbr = cstr(curr_year)[-2:] + '-' + cstr(curr_year+1)[-2:]
-	return fy, stdt, abbr
+		fy = cstr(start_year) + '-' + cstr(start_year + 1)
+	return fy
 
 def create_taxes(args):
 	for i in xrange(1,6):
diff --git a/startup/report_data_map.py b/startup/report_data_map.py
index c1f9627..b981d55 100644
--- a/startup/report_data_map.py
+++ b/startup/report_data_map.py
@@ -12,8 +12,7 @@
 		"conditions": ["docstatus < 2"]
 	},
 	"Fiscal Year": {
-		"columns": ["name", "year_start_date", 
-			"adddate(adddate(year_start_date, interval 1 year), interval -1 day) as year_end_date"],
+		"columns": ["name", "year_start_date", "year_end_date"],
 		"conditions": ["docstatus < 2"],
 	},
 
diff --git a/stock/utils.py b/stock/utils.py
index 6d9f204..4f5e11a 100644
--- a/stock/utils.py
+++ b/stock/utils.py
@@ -299,6 +299,8 @@
 	mr_list = []
 	defaults = webnotes.defaults.get_defaults()
 	exceptions_list = []
+	from accounts.utils import get_fiscal_year
+	current_fiscal_year = get_fiscal_year(nowdate())[0] or defaults.fiscal_year
 	for request_type in material_requests:
 		for company in material_requests[request_type]:
 			try:
@@ -309,7 +311,7 @@
 				mr = [{
 					"doctype": "Material Request",
 					"company": company,
-					"fiscal_year": defaults.fiscal_year,
+					"fiscal_year": current_fiscal_year,
 					"transaction_date": nowdate(),
 					"material_request_type": request_type
 				}]
diff --git a/utilities/demo/demo_docs/Fiscal_Year.csv b/utilities/demo/demo_docs/Fiscal_Year.csv
index 09e8252..9cc6036 100644
--- a/utilities/demo/demo_docs/Fiscal_Year.csv
+++ b/utilities/demo/demo_docs/Fiscal_Year.csv
@@ -13,11 +13,11 @@
 ,,,,

 DocType:,Fiscal Year,,,

 Column Labels:,ID,Year Name,Year Start Date,Year Closed

-Column Name:,name,year,year_start_date,is_fiscal_year_closed

+Column Name:,name,year,year_start_date,year_end_date,is_fiscal_year_closed

 Mandatory:,Yes,Yes,Yes,No

 Type:,Data (text),Data,Date,Select

 Info:,,,,"One of: No, Yes"

 Start entering data below this line,,,,

-,,2009,01-Jan-2009,No

-,,2010,01-Jan-2010,No

-,,2011,01-Jan-2011,No
\ No newline at end of file
+,,2009,01-01-2009,31-12-2009,No

+,,2010,01-01-2010,31-12-2010,No

+,,2011,01-01-2011,31-12-2011,No
\ No newline at end of file