diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js index b45e1208ce..878c9ceca8 100644 --- a/erpnext/public/js/controllers/transaction.js +++ b/erpnext/public/js/controllers/transaction.js @@ -245,10 +245,15 @@ erpnext.TransactionController = erpnext.taxes_and_totals.extend({ }, get_exchange_rate: function(from_currency, to_currency, callback) { - var exchange_name = from_currency + "-" + to_currency; - frappe.model.with_doc("Currency Exchange", exchange_name, function(name) { - var exchange_doc = frappe.get_doc("Currency Exchange", exchange_name); - callback(exchange_doc ? flt(exchange_doc.exchange_rate) : 0); + frappe.call({ + method: "erpnext.setup.utils.get_exchange_rate", + args: { + from_currency: from_currency, + to_currency: to_currency + }, + callback: function(r) { + callback(flt(r.message)); + } }); }, diff --git a/erpnext/setup/doctype/currency_exchange/currency_exchange.py b/erpnext/setup/doctype/currency_exchange/currency_exchange.py index 17a103764b..6022812975 100644 --- a/erpnext/setup/doctype/currency_exchange/currency_exchange.py +++ b/erpnext/setup/doctype/currency_exchange/currency_exchange.py @@ -9,7 +9,6 @@ from frappe import _ from frappe.model.document import Document class CurrencyExchange(Document): - def autoname(self): self.name = self.from_currency + "-" + self.to_currency diff --git a/erpnext/setup/utils.py b/erpnext/setup/utils.py index e3a034c787..2923f67a63 100644 --- a/erpnext/setup/utils.py +++ b/erpnext/setup/utils.py @@ -58,6 +58,20 @@ def before_tests(): frappe.db.sql("delete from `tabItem Price`") frappe.db.commit() +@frappe.whitelist() def get_exchange_rate(from_currency, to_currency): - exchange = "%s-%s" % (from_currency, to_currency) - return flt(frappe.db.get_value("Currency Exchange", exchange, "exchange_rate")) + if frappe.conf.jsonrates_api_key: + 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://jsonrates.com/get/?from={0}&to={1}&apiKey={2}".format(from_currency, + to_currency, frappe.conf.jsonrates_api_key)) + # expire in 24 hours + value = response.json().get("rate") + cache.setex(key, value, 24 * 60 * 60) + return flt(value) + else: + exchange = "%s-%s" % (from_currency, to_currency) + return flt(frappe.db.get_value("Currency Exchange", exchange, "exchange_rate"))