2023-05-22 19:48:44 +00:00
|
|
|
|
package utils
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"math"
|
|
|
|
|
|
2023-06-22 08:26:42 +00:00
|
|
|
|
"github.com/danilsolovyov/croupierCbrf/internal/dal"
|
2023-05-22 19:48:44 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func CurrencyExchange(currencies map[string]dal.Quote, fromCurrency, toCurrency string, amount int64) (int64, error) {
|
|
|
|
|
fromRate, ok := currencies[fromCurrency]
|
|
|
|
|
if !ok && fromCurrency != dal.DefaultCurrency {
|
|
|
|
|
return 0, fmt.Errorf("Курс для валюты %s не найден", fromCurrency)
|
|
|
|
|
}
|
|
|
|
|
if fromCurrency == dal.DefaultCurrency {
|
|
|
|
|
fromRate.Value = 1
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
toRate, ok := currencies[toCurrency]
|
|
|
|
|
if !ok && toCurrency != dal.DefaultCurrency {
|
|
|
|
|
return 0, fmt.Errorf("Курс для валюты %s не найден", toCurrency)
|
|
|
|
|
}
|
|
|
|
|
if toCurrency == dal.DefaultCurrency {
|
|
|
|
|
toRate.Value = 1
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Округляем число курса 79.9093 => 79.91
|
|
|
|
|
roundedFromValue := math.Round(fromRate.Value*100) / 100
|
|
|
|
|
roundedToValue := math.Round(toRate.Value*100) / 100
|
|
|
|
|
|
|
|
|
|
// Переводим сумму из одной валюты в рубли
|
|
|
|
|
amountInRubles := float64(amount) * roundedFromValue
|
|
|
|
|
|
|
|
|
|
// Переводим рубли в нужную валюту и округляем до ближайшего целого числа
|
|
|
|
|
result := int64(amountInRubles / roundedToValue)
|
|
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
|
}
|