Merge branch 'develop' into exchange_rate_modifications
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.js b/erpnext/accounts/doctype/journal_entry/journal_entry.js
index ced56d0..c3a5090 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.js
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.js
@@ -420,6 +420,7 @@
 			frappe.call({
 				method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_exchange_rate",
 				args: {
+					posting_date: frm.doc.posting_date,
 					account: row.account,
 					account_currency: row.account_currency,
 					company: frm.doc.company,
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py
index 4e00c32..2a6d276 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.py
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py
@@ -310,8 +310,9 @@
 			if d.account_currency == self.company_currency:
 				d.exchange_rate = 1
 			elif not d.exchange_rate or d.exchange_rate == 1 or \
-				(d.reference_type in ("Sales Invoice", "Purchase Invoice") and d.reference_name):
-					d.exchange_rate = get_exchange_rate(d.account, d.account_currency, self.company,
+				(d.reference_type in ("Sales Invoice", "Purchase Invoice") and d.reference_name and d.posting_date):
+                    # Modified to include the posting date for which to retreive the exchange rate
+					d.exchange_rate = get_exchange_rate(self.posting_date, d.account, d.account_currency, self.company,
 						d.reference_type, d.reference_name, d.debit, d.credit, d.exchange_rate)
 
 			if not d.exchange_rate:
@@ -631,7 +632,8 @@
 	cost_center = frappe.db.get_value("Company", ref_doc.company, "cost_center")
 	exchange_rate = 1
 	if args.get("party_account"):
-		exchange_rate = get_exchange_rate(args.get("party_account"), args.get("party_account_currency"),
+        # Modified to include the posting date for which the exchange rate is required. Assumed to be the posting date in the reference document
+		exchange_rate = get_exchange_rate(ref_doc.posting_date, args.get("party_account"), args.get("party_account_currency"),
 			ref_doc.company, ref_doc.doctype, ref_doc.name)
 
 	je = frappe.new_doc("Journal Entry")
@@ -664,7 +666,9 @@
 	bank_account = get_default_bank_cash_account(ref_doc.company, "Bank", account=args.get("bank_account"))
 	if bank_account:
 		bank_row.update(bank_account)
-		bank_row.exchange_rate = get_exchange_rate(bank_account["account"],
+        # Modified to include the posting date for which the exchange rate is required. Assumed to be the posting date of the 
+        # reference date
+		bank_row.exchange_rate = get_exchange_rate(ref_doc.posting_date, bank_account["account"],
 			bank_account["account_currency"], ref_doc.company)
 
 	bank_row.cost_center = cost_center
@@ -787,7 +791,9 @@
 		"party_type": party_type,
 		"account_type": account_details.account_type,
 		"account_currency": account_details.account_currency or company_currency,
-		"exchange_rate": get_exchange_rate(account, account_details.account_currency,
+        # The date used to retreive the exchange rate here is the date passed in as an argument to this function. 
+        # It is assumed to be the date on which the balance is sought
+		"exchange_rate": get_exchange_rate(date, account, account_details.account_currency,
 			company, debit=debit, credit=credit, exchange_rate=exchange_rate)
 	}
 
@@ -797,8 +803,9 @@
 
 	return grid_values
 
+# Added posting_date as one of the parameters of get_exchange_rate
 @frappe.whitelist()
-def get_exchange_rate(account, account_currency=None, company=None,
+def get_exchange_rate(posting_date, account, account_currency=None, company=None,
 		reference_type=None, reference_name=None, debit=None, credit=None, exchange_rate=None):
 	from erpnext.setup.utils import get_exchange_rate
 	account_details = frappe.db.get_value("Account", account,
@@ -824,8 +831,9 @@
 				(account_details.root_type == "Liability" and debit)):
 			exchange_rate = get_average_exchange_rate(account)
 
-		if not exchange_rate and account_currency:
-			exchange_rate = get_exchange_rate(account_currency, company_currency)
+		if not exchange_rate and account_currency and posting_date:
+            # The date used to retreive the exchange rate here is the date passed in as an argument to this function. 
+			exchange_rate = get_exchange_rate(posting_date, account_currency, company_currency)
 
 	else:
 		exchange_rate = 1
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.js b/erpnext/accounts/doctype/payment_entry/payment_entry.js
index 5e6fc53..ae956c6 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.js
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.js
@@ -356,6 +356,7 @@
 		frappe.call({
 			method: "erpnext.setup.utils.get_exchange_rate",
 			args: {
+				posting_date: frm.doc.posting_date,
 				from_currency: from_currency,
 				to_currency: to_currency
 			},
@@ -448,6 +449,7 @@
 			method: 'erpnext.accounts.doctype.payment_entry.payment_entry.get_outstanding_reference_documents',
 			args: {
 				args: {
+					"posting_date": frm.doc.posting_date,
 					"company": frm.doc.company,
 					"party_type": frm.doc.party_type,
 					"payment_type": frm.doc.payment_type,
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py
index 179a321..314e814 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py
@@ -145,11 +145,11 @@
 			elif self.payment_type in ("Pay", "Internal Transfer"):
 				self.source_exchange_rate = get_average_exchange_rate(self.paid_from)
 			else:
-				self.source_exchange_rate = get_exchange_rate(self.paid_from_account_currency, 
+				self.source_exchange_rate = get_exchange_rate(self.posting_date, self.paid_from_account_currency, 
 					self.company_currency)
 		
 		if self.paid_to and not self.target_exchange_rate:
-			self.target_exchange_rate = get_exchange_rate(self.paid_to_account_currency, 
+			self.target_exchange_rate = get_exchange_rate(self.posting_date, self.paid_to_account_currency, 
 				self.company_currency)
 				
 	def validate_mandatory(self):
@@ -475,12 +475,12 @@
 				d["exchange_rate"] = frappe.db.get_value(d.voucher_type, d.voucher_no, "conversion_rate")
 
 	# Get all SO / PO which are not fully billed or aginst which full advance not paid
-	orders_to_be_billed =  get_orders_to_be_billed(args.get("party_type"), args.get("party"), 
+	orders_to_be_billed =  get_orders_to_be_billed(args.get("posting_date"),args.get("party_type"), args.get("party"), 
 		party_account_currency, company_currency)
 	
 	return negative_outstanding_invoices + outstanding_invoices + orders_to_be_billed
 	
-def get_orders_to_be_billed(party_type, party, party_account_currency, company_currency):
+def get_orders_to_be_billed(posting_date, party_type, party, party_account_currency, company_currency):
 	voucher_type = 'Sales Order' if party_type == "Customer" else 'Purchase Order'
 
 	ref_field = "base_grand_total" if party_account_currency == company_currency else "grand_total"
@@ -510,7 +510,8 @@
 	order_list = []
 	for d in orders:
 		d["voucher_type"] = voucher_type
-		d["exchange_rate"] = get_exchange_rate(party_account_currency, company_currency)
+        # This assumes that the exchange rate required is the one in the SO
+		d["exchange_rate"] = get_exchange_rate(posting_date,party_account_currency, company_currency)
 		order_list.append(d)
 
 	return order_list
@@ -585,14 +586,16 @@
 			exchange_rate = 1
 		else:
 			total_amount = ref_doc.grand_total
+            # Get the exchange rate from the original ref doc or get it based on the posting date of the ref doc
 			exchange_rate = ref_doc.get("conversion_rate") or \
-				get_exchange_rate(party_account_currency, ref_doc.company_currency)
+				get_exchange_rate(ref_doc.posting_date, party_account_currency, ref_doc.company_currency)
 		
 		outstanding_amount = ref_doc.get("outstanding_amount") \
 			if reference_doctype in ("Sales Invoice", "Purchase Invoice") \
 			else flt(total_amount) - flt(ref_doc.advance_paid)			
 	else:
-		exchange_rate = get_exchange_rate(party_account_currency, ref_doc.company_currency)
+        # Get the exchange rate based on the posting date of the ref doc
+		exchange_rate = get_exchange_rate(ref_doc.posting_date, party_account_currency, ref_doc.company_currency)
 		
 	return frappe._dict({
 		"due_date": ref_doc.get("due_date"),
diff --git a/erpnext/accounts/doctype/payment_request/test_payment_request.py b/erpnext/accounts/doctype/payment_request/test_payment_request.py
index 73c412f..d695bf6 100644
--- a/erpnext/accounts/doctype/payment_request/test_payment_request.py
+++ b/erpnext/accounts/doctype/payment_request/test_payment_request.py
@@ -9,6 +9,7 @@
 from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.setup.utils import get_exchange_rate
+from frappe.utils import nowdate
 # test_records = frappe.get_test_records('Payment Request')
 
 test_dependencies = ["Currency Exchange", "Journal Entry", "Contact", "Address"]
@@ -52,7 +53,7 @@
 		self.assertEquals(pr.reference_name, so_inr.name)
 		self.assertEquals(pr.currency, "INR")
 
-		conversion_rate = get_exchange_rate("USD", "INR")
+		conversion_rate = get_exchange_rate(nowdate(), "USD", "INR")
 
 		si_usd = create_sales_invoice(currency="USD", conversion_rate=conversion_rate)
 		pr = make_payment_request(dt="Sales Invoice", dn=si_usd.name, recipient_id="saurabh@erpnext.com")
diff --git a/erpnext/accounts/doctype/sales_invoice/pos.py b/erpnext/accounts/doctype/sales_invoice/pos.py
index 5ed25b4..f0db4ea 100644
--- a/erpnext/accounts/doctype/sales_invoice/pos.py
+++ b/erpnext/accounts/doctype/sales_invoice/pos.py
@@ -57,7 +57,7 @@
 	doc.currency = pos_profile.get('currency') or company_data.default_currency
 	doc.conversion_rate = 1.0
 	if doc.currency != company_data.default_currency:
-		doc.conversion_rate = get_exchange_rate(doc.currency, company_data.default_currency)
+		doc.conversion_rate = get_exchange_rate(doc.posting_date, doc.currency, company_data.default_currency)
 	doc.selling_price_list = pos_profile.get('selling_price_list') or \
 		frappe.db.get_value('Selling Settings', None, 'selling_price_list')
 	doc.naming_series = pos_profile.get('naming_series') or 'SINV-'
diff --git a/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.py b/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.py
index 1793fc3..2b024ef 100644
--- a/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.py
+++ b/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.py
@@ -3,6 +3,7 @@
 
 from __future__ import unicode_literals
 from erpnext.setup.utils import get_exchange_rate
+from erpnext.utils import nowdate
 
 import frappe
 
@@ -39,7 +40,7 @@
 		#Add a row for each supplier
 		for root in set(suppliers):
 			supplier_currency = frappe.db.get_value("Supplier",root,"default_currency")
-			exg = get_exchange_rate(supplier_currency,company_currency)
+			exg = get_exchange_rate(nowdate(),supplier_currency,company_currency)
 
 			row = frappe._dict({
 				"supplier_name": root
diff --git a/erpnext/crm/doctype/opportunity/opportunity.py b/erpnext/crm/doctype/opportunity/opportunity.py
index 8bd3a23..fafc44b 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.py
+++ b/erpnext/crm/doctype/opportunity/opportunity.py
@@ -202,7 +202,7 @@
 		if company_currency == quotation.currency:
 			exchange_rate = 1
 		else:
-			exchange_rate = get_exchange_rate(quotation.currency, company_currency)
+			exchange_rate = get_exchange_rate(quotation.transaction_date, quotation.currency, company_currency)
 
 		quotation.conversion_rate = exchange_rate
 
diff --git a/erpnext/demo/user/purchase.py b/erpnext/demo/user/purchase.py
index ab8ec77..c7ec62b 100644
--- a/erpnext/demo/user/purchase.py
+++ b/erpnext/demo/user/purchase.py
@@ -12,6 +12,7 @@
 from erpnext.stock.doctype.material_request.material_request import make_request_for_quotation
 from erpnext.buying.doctype.request_for_quotation.request_for_quotation import \
 			 make_supplier_quotation as make_quotation_from_rfq
+from frappe.utils.nowdate
 
 def work():
 	frappe.set_user(frappe.db.get_global('demo_purchase_user'))
@@ -56,7 +57,7 @@
 	if company_currency == party_account_currency:
 		exchange_rate = 1
 	else:
-		exchange_rate = get_exchange_rate(party_account_currency, company_currency)
+		exchange_rate = get_exchange_rate(nowdate(), party_account_currency, company_currency)
 
 	# make supplier quotations
 	if random.random() < 0.2:
diff --git a/erpnext/demo/user/sales.py b/erpnext/demo/user/sales.py
index 10df143..b9e6535 100644
--- a/erpnext/demo/user/sales.py
+++ b/erpnext/demo/user/sales.py
@@ -9,6 +9,7 @@
 from erpnext.setup.utils import get_exchange_rate
 from erpnext.accounts.party import get_party_account_currency
 from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request, make_payment_entry
+from frappe.utils import nowdate
 
 def work():
 	frappe.set_user(frappe.db.get_global('demo_sales_user_2'))
@@ -88,7 +89,7 @@
 		if company_currency == party_account_currency:
 			exchange_rate = 1
 		else:
-			exchange_rate = get_exchange_rate(party_account_currency, company_currency)
+			exchange_rate = get_exchange_rate(nowdate(), party_account_currency, company_currency)
 
 		qtn = frappe.get_doc({
 			"creation": frappe.flags.current_date,
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index 34cbbae..78776a3 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -424,7 +424,7 @@
 		// Added `ignore_pricing_rule` to determine if document is loading after mapping from another doc
 		if(this.frm.doc.currency && this.frm.doc.currency !== company_currency
 				&& !this.frm.doc.ignore_pricing_rule) {
-			this.get_exchange_rate(this.frm.doc.currency, company_currency,
+			this.get_exchange_rate(this.frm.doc.posting_date, this.frm.doc.currency, company_currency,
 				function(exchange_rate) {
 					me.frm.set_value("conversion_rate", exchange_rate);
 				});
@@ -452,10 +452,11 @@
 		}
 	},
 
-	get_exchange_rate: function(from_currency, to_currency, callback) {
+	get_exchange_rate: function(posting_date, from_currency, to_currency, callback) {
 		return frappe.call({
 			method: "erpnext.setup.utils.get_exchange_rate",
 			args: {
+				posting_date: posting_date,
 				from_currency: from_currency,
 				to_currency: to_currency
 			},
@@ -472,7 +473,7 @@
 		var company_currency = this.get_company_currency();
 		// Added `ignore_pricing_rule` to determine if document is loading after mapping from another doc
 		if(this.frm.doc.price_list_currency !== company_currency  && !this.frm.doc.ignore_pricing_rule) {
-			this.get_exchange_rate(this.frm.doc.price_list_currency, company_currency,
+			this.get_exchange_rate(this.frm.doc.posting_date, this.frm.doc.price_list_currency, company_currency,
 				function(exchange_rate) {
 					me.frm.set_value("plc_conversion_rate", exchange_rate);
 				});
diff --git a/erpnext/setup/doctype/currency_exchange/currency_exchange.json b/erpnext/setup/doctype/currency_exchange/currency_exchange.json
index 1209bc1..4c62e9b 100644
--- a/erpnext/setup/doctype/currency_exchange/currency_exchange.json
+++ b/erpnext/setup/doctype/currency_exchange/currency_exchange.json
@@ -15,13 +15,41 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "columns": 0, 
+   "fieldname": "date", 
+   "fieldtype": "Date", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 1, 
+   "label": "Date", 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 1, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0, 
+   "width": "5"
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
    "fieldname": "from_currency", 
    "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
    "in_filter": 0, 
-   "in_list_view": 1, 
+   "in_list_view": 0, 
    "label": "From Currency", 
    "length": 0, 
    "no_copy": 0, 
@@ -34,19 +62,21 @@
    "reqd": 1, 
    "search_index": 0, 
    "set_only_once": 0, 
-   "unique": 0
+   "unique": 0, 
+   "width": "3"
   }, 
   {
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "columns": 0, 
    "fieldname": "to_currency", 
    "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
    "in_filter": 0, 
-   "in_list_view": 1, 
+   "in_list_view": 0, 
    "label": "To Currency", 
    "length": 0, 
    "no_copy": 0, 
@@ -59,12 +89,14 @@
    "reqd": 1, 
    "search_index": 0, 
    "set_only_once": 0, 
-   "unique": 0
+   "unique": 0, 
+   "width": "3"
   }, 
   {
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "columns": 0, 
    "fieldname": "exchange_rate", 
    "fieldtype": "Float", 
    "hidden": 0, 
@@ -84,7 +116,8 @@
    "reqd": 1, 
    "search_index": 0, 
    "set_only_once": 0, 
-   "unique": 0
+   "unique": 0, 
+   "width": "3"
   }
  ], 
  "hide_heading": 0, 
@@ -98,7 +131,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2016-07-25 05:24:26.264021", 
+ "modified": "2016-09-05 22:47:38.746711", 
  "modified_by": "Administrator", 
  "module": "Setup", 
  "name": "Currency Exchange", 
@@ -188,5 +221,8 @@
  "quick_entry": 1, 
  "read_only": 0, 
  "read_only_onload": 0, 
+ "sort_field": "name", 
+ "sort_order": "DESC", 
+ "title_field": "", 
  "track_seen": 0
 }
\ No newline at end of file
diff --git a/erpnext/setup/doctype/currency_exchange/currency_exchange.py b/erpnext/setup/doctype/currency_exchange/currency_exchange.py
index 6022812..7f1a43c 100644
--- a/erpnext/setup/doctype/currency_exchange/currency_exchange.py
+++ b/erpnext/setup/doctype/currency_exchange/currency_exchange.py
@@ -7,13 +7,15 @@
 import frappe
 from frappe import _
 from frappe.model.document import Document
+from frappe.utils import get_datetime, get_datetime_str, formatdate
 
 class CurrencyExchange(Document):
-	def autoname(self):
-		self.name = self.from_currency + "-" + self.to_currency
+    def autoname(self):
+        self.name = formatdate(get_datetime_str(self.date),"yyyy-MM-dd") + "-" + self.from_currency + "-" + self.to_currency
+        #self.name = self.date + "-" + self.from_currency + "-" + self.to_currency
 
-	def validate(self):
-		self.validate_value("exchange_rate", ">", 0)
+    def validate(self):
+        self.validate_value("exchange_rate", ">", 0)
 
-		if self.from_currency == self.to_currency:
-			frappe.throw(_("From Currency and To Currency cannot be same"))
+        if self.from_currency == self.to_currency:
+            frappe.throw(_("From Currency and To Currency cannot be same"))
diff --git a/erpnext/setup/doctype/currency_exchange/test_records.json b/erpnext/setup/doctype/currency_exchange/test_records.json
index 784bf26..17ca1a5 100644
--- a/erpnext/setup/doctype/currency_exchange/test_records.json
+++ b/erpnext/setup/doctype/currency_exchange/test_records.json
@@ -1,18 +1,21 @@
 [
  {
   "doctype": "Currency Exchange", 
+  "date": "01-01-2016",
   "exchange_rate": 60.0, 
   "from_currency": "USD", 
   "to_currency": "INR"
  }, 
  {
   "doctype": "Currency Exchange", 
+  "date": "01-01-2016",
   "exchange_rate": 0.773, 
   "from_currency": "USD", 
   "to_currency": "EUR"
  }, 
  {
   "doctype": "Currency Exchange", 
+  "date": "01-01-2016",
   "exchange_rate": 0.0167, 
   "from_currency": "INR", 
   "to_currency": "USD"
diff --git a/erpnext/setup/utils.py b/erpnext/setup/utils.py
index eda2042..c340cac 100644
--- a/erpnext/setup/utils.py
+++ b/erpnext/setup/utils.py
@@ -5,95 +5,95 @@
 import frappe
 from frappe import _, throw
 from frappe.utils import flt
+from frappe.utils import get_datetime, get_datetime_str
 
 def get_company_currency(company):
-	currency = frappe.db.get_value("Company", company, "default_currency", cache=True)
-	if not currency:
-		currency = frappe.db.get_default("currency")
-	if not currency:
-		throw(_('Please specify Default Currency in Company Master and Global Defaults'))
+    currency = frappe.db.get_value("Company", company, "default_currency", cache=True)
+    if not currency:
+        currency = frappe.db.get_default("currency")
+    if not currency:
+        throw(_('Please specify Default Currency in Company Master and Global Defaults'))
 
-	return currency
+    return currency
 
 def get_root_of(doctype):
-	"""Get root element of a DocType with a tree structure"""
-	result = frappe.db.sql_list("""select name from `tab%s`
-		where lft=1 and rgt=(select max(rgt) from `tab%s` where docstatus < 2)""" %
-		(doctype, doctype))
-	return result[0] if result else None
+    """Get root element of a DocType with a tree structure"""
+    result = frappe.db.sql_list("""select name from `tab%s`
+        where lft=1 and rgt=(select max(rgt) from `tab%s` where docstatus < 2)""" %
+        (doctype, doctype))
+    return result[0] if result else None
 
 def get_ancestors_of(doctype, name):
-	"""Get ancestor elements of a DocType with a tree structure"""
-	lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
-	result = frappe.db.sql_list("""select name from `tab%s`
-		where lft<%s and rgt>%s order by lft desc""" % (doctype, "%s", "%s"), (lft, rgt))
-	return result or []
+    """Get ancestor elements of a DocType with a tree structure"""
+    lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
+    result = frappe.db.sql_list("""select name from `tab%s`
+        where lft<%s and rgt>%s order by lft desc""" % (doctype, "%s", "%s"), (lft, rgt))
+    return result or []
 
 def before_tests():
-	frappe.clear_cache()
-	# complete setup if missing
-	from frappe.desk.page.setup_wizard.setup_wizard import setup_complete
-	if not frappe.get_list("Company"):
-		setup_complete({
-			"currency"			:"USD",
-			"first_name"		:"Test",
-			"last_name"			:"User",
-			"company_name"		:"Wind Power LLC",
-			"timezone"			:"America/New_York",
-			"company_abbr"		:"WP",
-			"industry"			:"Manufacturing",
-			"country"			:"United States",
-			"fy_start_date"		:"2011-01-01",
-			"fy_end_date"		:"2011-12-31",
-			"language"			:"english",
-			"company_tagline"	:"Testing",
-			"email"				:"test@erpnext.com",
-			"password"			:"test",
-			"chart_of_accounts" : "Standard",
-			"domain"			: "Manufacturing",
-			
-		})
+    frappe.clear_cache()
+    # complete setup if missing
+    from frappe.desk.page.setup_wizard.setup_wizard import setup_complete
+    if not frappe.get_list("Company"):
+        setup_complete({
+            "currency"            :"USD",
+            "first_name"        :"Test",
+            "last_name"            :"User",
+            "company_name"        :"Wind Power LLC",
+            "timezone"            :"America/New_York",
+            "company_abbr"        :"WP",
+            "industry"            :"Manufacturing",
+            "country"            :"United States",
+            "fy_start_date"        :"2011-01-01",
+            "fy_end_date"        :"2011-12-31",
+            "language"            :"english",
+            "company_tagline"    :"Testing",
+            "email"                :"test@erpnext.com",
+            "password"            :"test",
+            "chart_of_accounts" : "Standard",
+            "domain"            : "Manufacturing",
+            
+        })
 
-	frappe.db.sql("delete from `tabLeave Allocation`")
-	frappe.db.sql("delete from `tabLeave Application`")
-	frappe.db.sql("delete from `tabSalary Slip`")
-	frappe.db.sql("delete from `tabItem Price`")
+    frappe.db.sql("delete from `tabLeave Allocation`")
+    frappe.db.sql("delete from `tabLeave Application`")
+    frappe.db.sql("delete from `tabSalary Slip`")
+    frappe.db.sql("delete from `tabItem Price`")
 
-	frappe.db.set_value("Stock Settings", None, "auto_insert_price_list_rate_if_missing", 0)
+    frappe.db.set_value("Stock Settings", None, "auto_insert_price_list_rate_if_missing", 0)
 
-	frappe.db.commit()
+    frappe.db.commit()
 
 @frappe.whitelist()
-def get_exchange_rate(from_currency, to_currency):
-	if not (from_currency and to_currency):
-		return
-	
-	if from_currency == to_currency:
-		return 1
-	
-	exchange = "%s-%s" % (from_currency, to_currency)
-	value = flt(frappe.db.get_value("Currency Exchange", exchange, "exchange_rate"))
+def get_exchange_rate(posting_date, from_currency, to_currency):
+    if not (posting_date and from_currency and to_currency):
+        return
+    
+    if from_currency == to_currency:
+        return 1
+    
+    #Get all entries in Currency Exchange with from_currency and to_currency
+    entries = frappe.get_all("Currency Exchange", fields = ["*"], filters=[["date", "<=", get_datetime_str(posting_date)], ["from_currency", "=", from_currency], ["to_currency", "=", to_currency]], order_by="date desc")
+    if entries:
+        return flt(entries[0].exchange_rate)
 
-	if not value:
-		try:
-			cache = frappe.cache()
-			key = "currency_exchange_rate:{0}:{1}".format(from_currency, to_currency)
-			value = cache.get(key)
+    try:
+        cache = frappe.cache()
+        key = "currency_exchange_rate:{0}:{1}".format(from_currency, to_currency)
+        value = cache.get(key)
 
-			if not value:
-				import requests
-				response = requests.get("http://api.fixer.io/latest", params={
-					"base": from_currency,
-					"symbols": to_currency
-				})
-				# expire in 6 hours
-				response.raise_for_status()
-				value = response.json()["rates"][to_currency]
-				cache.setex(key, value, 6 * 60 * 60)
+        if not value:
+            import requests
+            response = requests.get("http://api.fixer.io/latest", params={
+                "base": from_currency,
+                "symbols": to_currency
+            })
+            # expire in 6 hours
+            response.raise_for_status()
+            value = response.json()["rates"][to_currency]
+            cache.setex(key, value, 6 * 60 * 60)
 
-			return flt(value)
-		except:
-			frappe.msgprint(_("Unable to find exchange rate for {0} to {1}").format(from_currency, to_currency))
-			return 0.0
-	else:
-		return value
+        return flt(value)
+    except:
+        frappe.msgprint(_("Unable to find exchange rate for {0} to {1} for key date {2}").format(from_currency, to_currency, posting_date))
+        return 0.0
\ No newline at end of file