Significantly improve exchange rate functionality (#2189)

* Redid the currency rate provider UI

* Bug fix, implemented the syncing functionality

* Changes for CSpell

* This should fix the test

* Updated the UI / wording, added the data attribution

* Small tweaks

* Fix the cache key I duplicated

* Very small fixes

* Also ensure we reference the old key when syncing

Otherwise the next update would unexpectedly break this for people because their old config wouldn't apply anymore

* Slight UI improvement

* Fix accidental capitalization
This commit is contained in:
Belle Aerni authored and GitHub committed 2024-03-21 08:41:35 -07:00
1 parent f9e9265043
commit b6686e7139
5 files changed
+318 -140

No files matched your search

+3 -1
View File
@@ -391,7 +391,9 @@
"ipify",
"hestiacp",
"intval",
"thisfiledoesnotexist"
"thisfiledoesnotexist",
"exchangerate",
"currencydata"
],
"ignorePaths": [
"tests-legacy/**",
+3 -33
View File
@@ -1,4 +1,5 @@
<?php
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
@@ -144,48 +145,17 @@ class Admin extends \Api_Abstract
/**
* Gets the API key for currencylayer.
*
* @since 4.22.0
*
* @return string
* @deprecated as this will only return the OLD key from before currency data got refactored. Current keys are stored in the module's config.
*/
public function get_key($data)
{
return $this->getService()->getKey();
}
/**
* Updates the API key for currencylayer.
*
* @since 4.22.0
*
* @return bool
*/
public function update_rate_settings($data)
{
$this->getService()->updateKey($data['currencylayer_key'] ?? null);
if ($data['crons_enabled'] ?? null == '1') {
$set = '1';
} else {
$set = '0';
}
$this->getService()->setCron($set);
return true;
}
/**
* See if CRON jobs are enabled for currency rates.
*
* @todo why does this even return a string instead of a boolean?
*
* @since 4.22.0
*
* @return string (0/1)
*/
public function is_cron_enabled($data)
public function is_cron_enabled($data): bool
{
return $this->getService()->isCronEnabled();
}
+176 -81
View File
@@ -1,4 +1,5 @@
<?php
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
@@ -10,8 +11,10 @@
namespace Box\Mod\Currency;
use FOSSBilling\InformationException;
use FOSSBilling\InjectionAwareInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\Cache\ItemInterface;
class Service implements InjectionAwareInterface
{
@@ -63,7 +66,7 @@ class Service implements InjectionAwareInterface
{
$f_rate = $this->getRateByCode($foreign_code);
if ($f_rate == 0) {
throw new \FOSSBilling\InformationException('Currency conversion rate cannot be zero');
throw new InformationException('Currency conversion rate cannot be zero');
}
return 1 / $f_rate;
@@ -327,7 +330,7 @@ class Service implements InjectionAwareInterface
public function rm(\Model_Currency $model)
{
if ($model->is_default) {
throw new \FOSSBilling\InformationException('Cannot remove default currency');
throw new InformationException('Cannot remove default currency');
}
if ($model->code === null || empty($model->code)) {
@@ -342,15 +345,9 @@ class Service implements InjectionAwareInterface
}
/**
* Returns the API credentials for currencylayer.
*
* @todo maybe make this extensible so people can choose their data provider?
*
* @since 4.22.0
*
* @return string
* Returns the old API key. Kept to ensure updating doesn't break a config
*/
public function getKey()
public function getKey(): string
{
$sql = 'SELECT `param`, `value` FROM setting';
$db = $this->di['db'];
@@ -360,60 +357,25 @@ class Service implements InjectionAwareInterface
return $pairs['currencylayer'] ?? '';
}
/**
* Updates the API credentials for currencylayer.
*
* @todo maybe make this extensible so people can choose their data provider?
*
* @since 4.22.0
*/
public function updateKey($key)
{
$sql = "INSERT INTO `setting` (`param`, `value`, `public`, `created_at`, `updated_at`) VALUES ('currencylayer', :key, '0', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()) ON DUPLICATE KEY UPDATE `value`=:key, `updated_at`=CURRENT_TIMESTAMP()";
$values = [':key' => $key];
$db = $this->di['db'];
$db->exec($sql, $values);
}
/**
* See if we should update exchange rates whenever the CRON jobs are run.
*
* @since 4.22.0
*
* @return bool
*/
public function isCronEnabled()
public function isCronEnabled(): bool
{
$config = $this->di['mod_config']('currency');
$sql = 'SELECT `param`, `value` FROM setting';
$db = $this->di['db'];
$pairs = $db->getAssoc($sql);
if (isset($pairs['currency_cron_enabled']) && $pairs['currency_cron_enabled'] == '1') {
// Keeping backwards compatibility with old settings
if (isset($pairs['currency_cron_enabled']) && $pairs['currency_cron_enabled'] == '1' && empty($config['sync_rate'])) {
return true;
} else {
} elseif (isset($pairs['currency_cron_enabled']) && $pairs['currency_cron_enabled'] == '0' && empty($config['sync_rate'])) {
return false;
}
}
/**
* Enable or disable updating exchange rates whenever the CRON jobs are run.
*/
public function setCron($data): void
{
$sql = "INSERT INTO `setting` (`param`, `value`, `public`, `created_at`, `updated_at`) VALUES ('currency_cron_enabled', :key, '0', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP()) ON DUPLICATE KEY UPDATE `value`=:key, `updated_at`=CURRENT_TIMESTAMP()";
if ($data == '1') {
$key = '1';
} else {
$key = '0';
return ($config['sync_rate'] ?? 'auto') !== 'never';
}
$values = [':key' => $key];
$db = $this->di['db'];
$db->exec($sql, $values);
}
public function toApiArray(\Model_Currency $model)
@@ -480,7 +442,7 @@ class Service implements InjectionAwareInterface
if (isset($conversionRate)) {
if (!is_numeric($conversionRate) || $conversionRate <= 0) {
throw new \FOSSBilling\InformationException('Currency rate is invalid', null, 151);
throw new InformationException('Currency rate is invalid', null, 151);
}
$model->conversion_rate = $conversionRate;
}
@@ -493,7 +455,7 @@ class Service implements InjectionAwareInterface
return true;
}
public function updateCurrencyRates($data)
public function updateCurrencyRates()
{
$dc = $this->getDefault();
@@ -522,50 +484,185 @@ class Service implements InjectionAwareInterface
}
/**
* Fetch exchange rates from external sources.
* Uses data from the European Central Bank and currencylayer when the base currencies are Euro and US Dollar respectively.
*
* @todo use HTTPClient instead of simplexml_load_file()
*
* @param string $from Short code for the base currency
* @param string $to Short code for the target currency
*
* @return float Exchange rate
* Gives a conversion rate between two currencies.
* Handles selecting the right function to query the data sources & passing the correct parameters.
*/
protected function _getRate($from, $to)
protected function _getRate(string $from, string $to): float|false
{
$from_Currency = urlencode($from);
$to_Currency = urlencode($to);
$config = $this->di['mod_config']('currency');
$validFor = match ($config['sync_rate'] ?? 'auto') {
'1h' => 3600,
'10m' => 600,
'5m' => 300,
'1m' => 60,
'never' => 0,
default => 86_400, // Intentionally matches '1d', 'auto', and anything else
};
if ($from_Currency == 'EUR' && empty($this->getKey())) {
$XML = simplexml_load_file('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
foreach ($XML->Cube->Cube->Cube as $rate) {
if ($rate['currency'] == $to_Currency) {
return (float) $rate['rate'];
}
if ($config['provider'] === 'currency_data_api') {
$key = $config['currencydata_key'] ?? $this->getKey();
if (empty($key)) {
throw new InformationException('You must configure your API key to use Currency Data API as an exchange rate data source.');
}
$rates = $this->getCurrencyDataRates($from, $validFor, $key);
} elseif ($config['provider'] === 'currencylayer') {
if (empty($config['currencylayer_key'])) {
throw new InformationException('You must configure your API key to use currencylayer as an exchange rate data source.');
}
$rates = $this->getCurrencyLayerRates($from, $validFor, $config['currencylayer_key']);
} else {
$key = $config['exchangerate_api_key'] ?? ''; // No key is OK here, we will just use the open API
if ($config['sync_rate'] ?? 'auto' === 'auto') {
$rates = $this->getExchangeRateAPIRates($from, 0, $key);
} else {
$rates = $this->getExchangeRateAPIRates($from, $validFor, $key);
}
}
if (isset($rates[$to]) && is_numeric($rates[$to])) {
return floatval($rates[$to]);
} else {
return false;
}
}
/**
* Gets the rates from https://www.exchangerate-api.com.
* Handles both their open API endpoint as well as the authenticated ones.
* Implements smart caching using their API provided next update time and will also alert us if the open endpoint goes EOL.
*/
protected function getExchangeRateAPIRates(string $from, int $validFor, string $key): array
{
$result = $this->di['cache']->get("exchangerate.api.$from.$key.$validFor", function (ItemInterface $item) use ($from, $validFor, $key) {
$from_currency = urlencode($from);
if (!empty($key)) {
$key = urlencode($key);
$requestUrl = "https://v6.exchangerate-api.com/v6/$key/latest/$from_currency";
} else {
$requestUrl = 'https://open.er-api.com/v6/latest/USD';
}
throw new \FOSSBilling\Exception('Failed to get currency rates for :currency from the European Central Bank API', [':currency' => $to_Currency]);
$client = HttpClient::create(['bindto' => BIND_TO]);
$response = $client->request('GET', $requestUrl);
$array = $response->toArray();
if ($array['result'] !== 'success') {
$item->expiresAfter(15 * 60 * 60); // Try again in 15 min
error_log('ExchangeRate-API Gave an error: ' . $array['error-type']);
throw new \FOSSBilling\Exception('There was an error when fetching currency rates from ExchangeRate-API. See the error log for details.');
}
if ($validFor === 0) {
// ExchangeRate-API is great and will tell us exactly when the data will next have an update, so we will use that for the cache expiration when "auto" is the sync mode.
$item->expiresAt(new \DateTime($array['time_next_update_utc']));
} else {
$item->expiresAfter($validFor);
}
return $array;
});
// Their open access API endpoint has a specific param to inform of if it ever goes EOL, so let's monitor that and trigger an error to alert us if it's deprecated
if (array_key_exists('time_eol_unix', $result) && $result['time_eol_unix'] !== 0) {
trigger_error('ExchangeRate-API has deprecated their open endpoint. Investigate!', E_USER_DEPRECATED); // Should be sent via error reporting, making monitoring this easy
}
// Different array key between the open and authenticated endpoint, but otherwise it's the same structure.
if (!empty($key)) {
return $result['conversion_rates'] ?? [];
} else {
return $result['rates'] ?? [];
}
}
/**
* Gets the rates from https://apilayer.com/marketplace/currency_data-api.
* Fetches a complete list off currencies and then caches that result for the specified period.
* Normalizes the return array.
*/
protected function getCurrencyDataRates(string $from, int $validFor, string $key)
{
$result = $this->di['cache']->get("currency.data.api.$from.$key.$validFor", function (ItemInterface $item) use ($from, $validFor, $key) {
$item->expiresAfter($validFor);
$from_currency = urlencode($from);
$client = HttpClient::create(['bindto' => BIND_TO]);
$response = $client->request('GET', 'https://api.apilayer.com/currency_data/live', [
'query' => [
'currencies' => $to_Currency,
'source' => $from_Currency,
'source' => $from_currency,
],
'headers' => [
'Content-Type' => 'text/plain',
'apikey' => $this->getKey(),
'apikey' => $key,
],
]);
$array = $response->toArray();
if ($array['success'] !== true) {
throw new \FOSSBilling\Exception('<b>Currencylayer threw an error:</b><br />:errorInfo', [':errorInfo' => $array['error']['info']]);
} else {
return (float) $array['quotes'][$from_Currency . $to_Currency];
error_log($array['error']['info']);
throw new \FOSSBilling\Exception('There was an error when fetching currency rates from Currency Data API. See the error log for details.');
}
return $array;
});
return $this->processApiLayerFormat($result, $from);
}
/**
* Gets the rates from https://currencylayer.com/.
* Fetches a complete list off currencies and then caches that result for the specified period.
* Normalizes the return array.
*/
protected function getCurrencyLayerRates(string $from, int $validFor, string $key)
{
$result = $this->di['cache']->get("currencylayer.$from.$key.$validFor", function (ItemInterface $item) use ($from, $validFor, $key) {
$item->expiresAfter($validFor);
$from_currency = urlencode($from);
$client = HttpClient::create(['bindto' => BIND_TO]);
$response = $client->request('GET', 'https://api.apilayer.com/currency_data/live', [
'query' => [
'access_key' => $key,
'source' => $from_currency,
],
]);
$array = $response->toArray();
if ($array['success'] !== true) {
error_log($array['error']['info']);
throw new \FOSSBilling\Exception('There was an error when fetching currency rates from currencylayer. See the error log for details.');
}
return $array;
});
return $this->processApiLayerFormat($result, $from);
}
/**
* Normalizes the response from Currency Data API / currencylayer.
*/
private function processApiLayerFormat(array $result, string $from): array
{
$rates = [];
$prefixLen = strlen($from);
foreach ($result['quotes'] as $key => $rate) {
if (!is_numeric($rate)) {
continue;
}
// All values are prefixed with our 'from' currency (EX: 'USDAUD'), so strip that off before storing it.
$strippedName = substr($key, $prefixLen);
$rates[$strippedName] = $rate;
}
return $rates;
}
public function deleteCurrencyByCode($code)
@@ -590,8 +687,6 @@ class Service implements InjectionAwareInterface
/**
* If enabled, automatically call _getRate to fetch exchange rates whenever CRON jobs are run.
*
* @since 4.22.0
*/
public static function onBeforeAdminCronRun(\Box_Event $event)
{
@@ -600,7 +695,7 @@ class Service implements InjectionAwareInterface
try {
if ($currencyService->isCronEnabled()) {
$currencyService->updateCurrencyRates('');
$currencyService->updateCurrencyRates();
}
} catch (\Exception $e) {
error_log($e);
@@ -3,6 +3,8 @@
{% import 'macro_functions.html.twig' as mf %}
{% set active_menu = 'system' %}
{% set params = admin.extension_config_get({ 'ext': 'mod_currency' }) %}
{% set old_key = admin.currency_get_key %}
{% block meta_title %}{{ 'Currency settings'|trans }}{% endblock %}
@@ -37,7 +39,7 @@
</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" href="#tab-api-settings" data-bs-toggle="tab" role="tab">{{ 'Settings'|trans }}</a>
<a class="nav-link" href="#tab-api-settings" data-bs-toggle="tab" role="tab">{{ 'Integrations / Automation'|trans }}</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" href="#tab-converter" data-bs-toggle="tab" role="tab">{{ 'Converter'|trans }}</a>
@@ -48,8 +50,17 @@
<div class="tab-pane fade show active" id="tab-currencies" role="tabpanel">
<div class="card-body border-bottom">
<h3 class="card-title">{{ 'Manage currencies'|trans }}</h3>
<p class="card-subtitle">{{ 'The default currency is the one you define product pricing in. If your client chooses a different currency, pricing will be recalculated according to the conversion rate. You can have only one default currency. You cannot add multiple instances of the same currency. Changing the default currency after orders have been placed may have unexpected issues. Nothing is recalculated on default currency change. Your income is calculated in the default currency. Changing the default currency after you have paid invoices will distort income statistics. Currency rates are taken from the European Central Bank and currencylayer.'|trans }}</p>
<p class="card-subtitle">{{ 'The default currency is the one you define product pricing in. If your client chooses a different currency, pricing will be recalculated according to the conversion rate. Changing the default currency after orders have been placed may have unexpected issues. Nothing is recalculated on default currency change. Your income is calculated in the default currency. Changing the default currency after you have paid invoices will distort income statistics.'|trans }}</p>
</div>
{% if params.sync_rate != 'never' %}
<div class="alert alert-success" role="alert">
{{ 'FOSSBilling is configured to automatically sync currency exchange rates.'|trans }}
</div>
{% else %}
<div class="alert alert-warning" role="alert">
{{ 'FOSSBilling is not configured to automatically sync currency exchange rates.'|trans }}
</div>
{% endif %}
<div class="table-responsive">
<table class="table card-table table-vcenter table-striped text-nowrap">
<thead>
@@ -116,6 +127,9 @@
</svg>
<span>{{ 'Update Rates'|trans }}</span>
</a>
{% if params.provider == "exchangerate-api" %}
<a href="https://www.exchangerate-api.com" target="_blank"><p class="mt-1 mb-0">{{ 'Currency exchange rates By ExchangeRate-API.'|trans }}</p></a>
{% endif %}
</div>
</div>
@@ -155,37 +169,89 @@
</div>
<div class="tab-pane fade" id="tab-api-settings" role="tabpanel">
<form method="post" action="{{ 'api/admin/currency/update_rate_settings'|link }}" class="api-form" data-api-msg="{{ 'Successfully updated settings'|trans }}">
<form method="post" action="{{ 'api/admin/extension/config_save'|link }}" class="api-form" data-api-msg="{{ 'Successfully updated settings'|trans }}">
<input type="hidden" name="CSRFToken" value="{{ CSRFToken }}">
<input type="hidden" name="ext" value="mod_currency">
<div class="card-body">
<h3 class="card-title">{{ 'Adjust settings for currency rate updater'|trans }}</h3>
<div class="card-subtitle">
<p>FOSSBilling uses data retrieved from <a href="https://www.ecb.europa.eu/home/html/index.en.html" target="_blank">European Central Bank</a> for conversions from Euro to other currencies, and <a href="https://currencylayer.com/" target="_blank">Currencylayer</a> for conversations from US Dollar to other currencies.</p>
<p>If you choose Euro as your default currency, data from European Central Bank will be used, if you choose US Dollar, data from Currencylayer will be used.</p>
<p>As the European Central Bank has decided to keep its API free to everyone, you won't need an authorization key to use the ECB data. However, you'll need an API key to use Currencylayer.</p>
<p>The API key can be obtained from Currencylayer's <a href="https://currencylayer.com/product" target="_blank">website</a>. Please be informed that FOSSBilling does not generate any profits from your transactions on currencylayer.com.</p>
</div>
<div class="row">
<div class="col-md-11">
<div class="alert alert-warning" role="alert">
<h4 class="alert-title">WARNING!</h4>
<div class="text-muted">FOSSBilling is not responsible for any information obtained from third-party sources, specifically, the <a href="https://apilayer.com/" target="_blank">APILayer</a>, who are the rightful owners of Currencylayer API and the <a href="https://www.ecb.europa.eu/home/html/index.en.html" target="_blank">European Central Bank</a>.</div>
</div>
<h3 class="card-title">{{ 'Available exchange rate data providers'|trans }}</h3>
<p>{{ 'FOSSBilling provides integration with various currency exchange rate data providers, allowing you to choose whichever one best suits your needs. By default, FOSSBilling will use the ExchangeRate-API "Open Access Endpoint" which does not require any configuration.'|trans }}</p>
<table class="table">
<thead>
<tr>
<th>{{ 'Provider'|trans }}</th>
<th>{{ 'Authentication Required'|trans }}</th>
<th>{{ 'Update Frequency'|trans }}</th>
<th>{{ 'Supported Currencies'|trans }}</th>
<th>{{ 'Pricing'|trans }}</th>
</tr>
</thead>
<tbody>
<tr>
<th><a href="https://www.exchangerate-api.com/docs/free" target="_blank">{{ 'ExchangeRate-API (Open Access Endpoint)'|trans }}</a></th>
<th>✖️</th>
<th>{{ '1D'|trans }}</th>
<th><a href="https://www.exchangerate-api.com/docs/supported-currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
<th>{{ 'Free'|trans }}</th>
</tr>
<tr>
<th><a href="https://www.exchangerate-api.com/#pricing" target="_blank">ExchangeRate-API</a></th>
<th>☑️</th>
<th>{{ '1D / 1H / 5M'|trans }}</th>
<th><a href="https://www.exchangerate-api.com/docs/supported-currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
<th>{{ 'Free / paid'|trans }}</th>
</tr>
<tr>
<th><a href="https://apilayer.com/marketplace/currency_data-api" target="_blank">Currency Data API</a></th>
<th>☑️</th>
<th>{{ '1D / 1H / 10M / 1M'|trans }}</th>
<th><a href="https://currencylayer.com/currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
<th>{{ 'Free / paid'|trans }}</th>
</tr>
<tr>
<th><a href="https://currencylayer.com/" target="_blank">currencylayer</a></th>
<th>☑️</th>
<th>{{ '1D / 1H / 10M / 1M'|trans }}</th>
<th><a href="https://currencylayer.com/currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
<th>{{ 'Free / paid'|trans }}</th>
</tr>
</tbody>
</table>
<span class="text-muted">{{ 'When using ExchangeRate-API, their API informs FOSSBilling when the next update will occur which makes it more efficient for automated exchange rate syncing.'|trans }}</span>
<br/>
<span class="text-muted">{{ 'To the best of our knowledge, "Currency Data API" and "currencylayer" are both owned by APILayer and provide the same data, but through a different API.'|trans }}</span>
<div class="form-group mb-3 mt-3 row">
<label class="col-md-3 col-form-label">{{ 'Currency exchange rate data provider'|trans }}</label>
<div class="col-md-6">
<select class="form-select" aria-label="Currency data provider selection" name="provider" id="provider_select">
<option value="exchangerate-api" selected>ExchangeRate-API</option>
<option value="currency_data_api">Currency Data API</option>
<option value="currencylayer">currencylayer</option>
</select>
</div>
</div>
<div class="form-group mb-3 row">
<label class="col-md-3 col-form-label">{{ 'Currencylayer API key'|trans }}</label>
<label class="col-md-3 col-form-label">{{ 'API key'|trans }}</label>
<div class="col-md-6">
<input class="form-control" type="text" name="currencylayer_key" value="{{ admin.currency_get_key }}">
<input class="form-control" type="text" name="currencydata_key" id="currencydata" value="{{ params.currencydata_key|default(old_key) }}" hidden="true">
<input class="form-control" type="text" name="currencylayer_key" id="currencylayer" value="{{ params.currencylayer_key }}" hidden="true">
<input class="form-control" type="text" name="exchangerate_api_key" id="exchangerate_api" value="{{ params.exchangerate_api_key }}" hidden="true">
<span class="text-muted" id="exchangerate_api_help_text" hidden="true">{{ 'Leave this blank to use the ExchangeRate-API "Open Access Endpoint".'|trans }}</span>
</div>
</div>
<div class="form-group mb-3 row">
<label class="col-md-3 form-label">{{ 'Enable CRON jobs'|trans }}</label>
<label class="col-md-3 col-form-label">{{ 'Automatic sync rate'|trans }}</label>
<div class="col-md-6">
<label class="form-check form-switch">
<input class="form-check-input" name="crons_enabled" type="checkbox" value="1" {% if admin.currency_is_cron_enabled %} checked{% endif %}>
</label>
<small class="form-hint">{{ 'If you enable this, conversion rates will be automatically updated whenever the CRON job fires up. This should only be used if you have a paid subscription for Currencylayer, as otherwise you will quickly hit your rate limit.'|trans }}</small>
<select class="form-select" aria-label="Currency data provider selection" name="sync_rate" id="sync_rate">
<option value="auto" id="auto-sync" selected>{{ 'Auto'|trans }}</option>
<option value="never">{{ 'Never'|trans }}</option>
<option value="1d">{{ 'Daily'|trans }}</option>
<option value="1h">{{ 'Hourly'|trans }}</option>
<option value="10m">{{ 'Every 10 minutes'|trans }}</option>
<option value="5m">{{ 'Every 5 minutes'|trans }}</option>
<option value="1m" id="1m-sync">{{ 'Every minute'|trans }}</option>
</select>
<p class="text-muted">{{ '"Auto" is only available for ExchangeRate-API and when used will cause API requests to be made only when new data is made available, preventing excess requests.'|trans }}</p>
<p class="text-muted">{{ 'Exchange rate syncing runs via the cronjob and as such is limited by the frequency of your cron schedule (typically 5 minutes).'|trans }}</p>
</div>
</div>
</div>
@@ -226,5 +292,50 @@
return false;
};
function switchKeyBox(value){
if(value === 'currencylayer'){
document.getElementById("currencydata").hidden = true;
document.getElementById("currencylayer").hidden = false;
document.getElementById("exchangerate_api").hidden = true;
document.getElementById("exchangerate_api_help_text").hidden = true;
document.getElementById("auto-sync").disabled = true;
document.getElementById("1m-sync").disabled = false;
} else if(value === 'currency_data_api'){
document.getElementById("currencydata").hidden = false;
document.getElementById("currencylayer").hidden = true;
document.getElementById("exchangerate_api").hidden = true;
document.getElementById("exchangerate_api_help_text").hidden = true;
document.getElementById("auto-sync").disabled = true;
document.getElementById("1m-sync").disabled = false;
} else {
document.getElementById("currencydata").hidden = true;
document.getElementById("currencylayer").hidden = true;
document.getElementById("exchangerate_api").hidden = false;
document.getElementById("exchangerate_api_help_text").hidden = false;
document.getElementById("auto-sync").disabled = false;
document.getElementById("1m-sync").disabled = true;
}
if(value === 'exchangerate-api'){
if(document.getElementById("sync_rate").value === '1m'){
document.getElementById("sync_rate").value = 'auto';
}
} else {
if(document.getElementById("sync_rate").value === 'auto'){
document.getElementById("sync_rate").value = '1d';
}
}
}
document.getElementById("provider_select").onchange = function() {
switchKeyBox(this.value);
};
document.addEventListener("DOMContentLoaded", (event) => {
document.getElementById("sync_rate").value = "{{ params.sync_rate }}";
document.getElementById("provider_select").value = "{{ params.provider }}";
switchKeyBox("{{ params.provider }}");
});
</script>
{% endblock %}
@@ -715,7 +715,7 @@ class ServiceTest extends \BBTestCase
->willReturn($model);
$service->expects($this->atLeastOnce())
->method('_getRate')
->willReturn(random_int(1, 50) / 10);
->willReturn(floatval(random_int(1, 50) / 10));
$bean = new \DummyBean();
$bean->is_default = 1;
@@ -757,7 +757,7 @@ class ServiceTest extends \BBTestCase
->willReturn($model);
$service->expects($this->atLeastOnce())
->method('_getRate')
->willReturn(null);
->willReturn(false);
$bean = new \DummyBean();
$bean->is_default = 0;