[enhancement] automatic exchange rates via jsonrates
This commit is contained in:
		
							parent
							
								
									43a7b36fcf
								
							
						
					
					
						commit
						66fa1ff878
					
				| @ -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)); | ||||
| 			} | ||||
| 		}); | ||||
| 	}, | ||||
| 
 | ||||
|  | ||||
| @ -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 | ||||
| 
 | ||||
|  | ||||
| @ -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")) | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user