Added 'Custom Exchange Rate' boolea setting

Removed Fixer.io exchange rate backend
This commit is contained in:
eeintech 2021-05-25 11:19:07 -04:00
parent 654d4ecf46
commit 93bfe4c5f1
7 changed files with 29 additions and 66 deletions

View File

@ -1,7 +1,5 @@
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings as inventree_settings
from djmoney import settings as djmoney_settings
from djmoney.contrib.exchange.backends.base import BaseExchangeBackend
from djmoney.contrib.exchange.models import Rate
@ -11,12 +9,12 @@ from common.models import InvenTreeSetting
def get_exchange_rate_backend():
""" Return the exchange rate backend set by user """
if 'InvenTreeManualExchangeBackend' in inventree_settings.EXCHANGE_BACKEND:
custom = InvenTreeSetting.get_setting('CUSTOM_EXCHANGE_RATES', False)
if custom:
return InvenTreeManualExchangeBackend()
elif 'InvenTreeFixerExchangeBackend' in inventree_settings.EXCHANGE_BACKEND:
return InvenTreeFixerExchangeBackend()
else:
raise ImproperlyConfigured('Exchange Backend wrongly configured')
return ExchangeRateHostBackend()
class InvenTreeManualExchangeBackend(BaseExchangeBackend):
@ -30,13 +28,14 @@ class InvenTreeManualExchangeBackend(BaseExchangeBackend):
name = 'inventree'
url = None
custom_rates = True
base_currency = None
currencies = []
def update_default_currency(self):
""" Update to base currency """
self.base_currency = InvenTreeSetting.get_setting('INVENTREE_DEFAULT_CURRENCY', inventree_settings.BASE_CURRENCY)
self.base_currency = InvenTreeSetting.get_setting('INVENTREE_DEFAULT_CURRENCY', 'USD')
def __init__(self, url=None):
""" Overrides init to update url, base currency and currencies """
@ -73,39 +72,23 @@ class InvenTreeManualExchangeBackend(BaseExchangeBackend):
return stored_rates
class InvenTreeFixerExchangeBackend(InvenTreeManualExchangeBackend):
class ExchangeRateHostBackend(InvenTreeManualExchangeBackend):
"""
Backend for updating currency exchange rates using Fixer.IO API
Backend for https://exchangerate.host/
"""
name = 'fixer'
access_key = None
def get_api_key(self):
""" Get API key from global settings """
fixer_api_key = InvenTreeSetting.get_setting('INVENTREE_FIXER_API_KEY', '').strip()
if not fixer_api_key:
# API key not provided
return None
self.access_key = fixer_api_key
name = "exchangerate.host"
def __init__(self):
""" Override init to get access_key from global settings """
self.url = "https://api.exchangerate.host/latest"
self.get_api_key()
self.custom_rates = False
if self.access_key is None:
raise ImproperlyConfigured("fixer.io API key is needed to use InvenTreeFixerExchangeBackend")
super().__init__(url=djmoney_settings.FIXER_URL)
super().__init__(url=self.url)
def get_params(self):
""" Returns parameters (access key) """
return {"access_key": self.access_key}
# No API key is required
return {}
def update_rates(self, base_currency=None):
""" Override update_rates method using currencies found in the settings
@ -135,18 +118,3 @@ class InvenTreeFixerExchangeBackend(InvenTreeManualExchangeBackend):
pass
return {}
class ExchangeRateHostBackend(SimpleExchangeBackend):
"""
Backend for https://exchangerate.host/
"""
name = "exchangerate.host"
def __init__(self):
self.url = "https://api.exchangerate.host/latest"
def get_params(self):
# No API key is required
return {}

View File

@ -513,8 +513,6 @@ CURRENCIES = CONFIG.get(
],
)
EXCHANGE_BACKEND = 'InvenTree.exchange.ExchangeRateHostBackend'
# Extract email settings from the config file
email_config = CONFIG.get('email', {})

View File

@ -163,12 +163,11 @@ def check_for_updates():
def update_exchange_rates():
"""
If an API key for fixer.io has been provided, attempt to update currency exchange rates
Update currency exchange rates
"""
try:
import common.models
from django.conf import settings
from InvenTree.exchange import ExchangeRateHostBackend
except AppRegistryNotReady:
# Apps not yet loaded!
@ -177,13 +176,11 @@ def update_exchange_rates():
backend = ExchangeRateHostBackend()
print(f"Updating exchange rates from {backend.url}")
currencies = ','.join(settings.CURRENCIES)
base = common.models.InvenTreeSetting.get_setting('INVENTREE_DEFAULT_CURRENCY')
print(f"Using base currency '{base}'")
backend.update_rates(base_currency=base, symbols=currencies)
backend.update_rates(base_currency=base)
def send_email(subject, body, recipients, from_email=None):

View File

@ -944,6 +944,8 @@ class CurrencySettingsView(FormView):
context['default_currency'] = exchange_rate_backend.base_currency
context['custom_rates'] = exchange_rate_backend.custom_rates
context['exchange_backend'] = exchange_rate_backend.name
return context
@ -959,7 +961,7 @@ class CurrencySettingsView(FormView):
stored_rates = exchange_rate_backend.get_stored_rates()
for field in form.fields:
if exchange_rate_backend.name.startswith('fixer-'):
if not exchange_rate_backend.custom_rates:
# Disable all the fields
form.fields[field].disabled = True
form.fields[field].initial = clean_decimal(stored_rates.get(field, 0))
@ -973,7 +975,7 @@ class CurrencySettingsView(FormView):
# Get exchange rate backend
exchange_rate_backend = self.get_exchange_rate_backend()
if exchange_rate_backend.name.startswith('fixer-'):
if not exchange_rate_backend.custom_rates:
# Refresh rate from Fixer.IO API
exchange_rate_backend.update_rates(base_currency=exchange_rate_backend.base_currency)
# Check if rates have been updated

View File

@ -87,6 +87,13 @@ class InvenTreeSetting(models.Model):
'choices': djmoney.settings.CURRENCY_CHOICES,
},
'CUSTOM_EXCHANGE_RATES': {
'name': _('Custom Exchange Rates'),
'description': _('Enable custom exchange rates'),
'validator': bool,
'default': False,
},
'INVENTREE_DOWNLOAD_FROM_URL': {
'name': _('Download from URL'),
'description': _('Allow download of remote images and files from external URL'),

View File

@ -62,13 +62,6 @@ currencies:
- JPY
- NZD
- USD
# Define base currency (can also be defined in the global settings)
# base_currency: USD
# Define exchange backend
# Choices are:
# - InvenTreeManualExchangeBackend
# - InvenTreeFixerExchangeBackend
exchange_backend: InvenTreeManualExchangeBackend
# Email backend configuration
# Ref: https://docs.djangoproject.com/en/dev/topics/email/

View File

@ -16,9 +16,7 @@
{% include "InvenTree/settings/header.html" %}
<tbody>
{% include "InvenTree/settings/setting.html" with key="INVENTREE_DEFAULT_CURRENCY" icon="fa-dollar-sign" %}
{% if 'fixer' in exchange_backend %}
{% include "InvenTree/settings/setting.html" with key="INVENTREE_FIXER_API_KEY" icon="fa-key" %}
{% endif %}
{% include "InvenTree/settings/setting.html" with key="CUSTOM_EXCHANGE_RATES" icon="fa-edit" %}
</tbody>
</table>
@ -33,7 +31,7 @@
{% csrf_token %}
{% load crispy_forms_tags %}
{% crispy form %}
{% if 'fixer' in exchange_backend %}
{% if custom_rates is False %}
<button type="submit" class='btn btn-primary'>{% trans "Refresh Exchange Rates" %}</button>
{% else %}
<button type="submit" class='btn btn-primary'>{% trans "Update Exchange Rates" %}</button>