diff --git a/RhSolutions.AddIn/AddIn/RhSolutionsFunctions.cs b/RhSolutions.AddIn/AddIn/RhSolutionsFunctions.cs index 88edc88..16fbd7d 100644 --- a/RhSolutions.AddIn/AddIn/RhSolutionsFunctions.cs +++ b/RhSolutions.AddIn/AddIn/RhSolutionsFunctions.cs @@ -152,9 +152,35 @@ public class RhSolutionsFunctions } else { - var article = skus.First().Id; IDatabaseClient databaseClient = RhSolutionsAddIn.ServiceProvider.GetService(); ICurrencyClient currencyClient = RhSolutionsAddIn.ServiceProvider.GetRequiredService(); + IMemoryCache memoryCache = RhSolutionsAddIn.ServiceProvider.GetRequiredService(); + var article = skus.First().Id; + DateTime date = dateField == 0 ? DateTime.Today : DateTime.FromOADate(dateField); + + if (!memoryCache.TryGetValue(date, out decimal exchangeRate)) + { + var result = ExcelAsyncUtil.Run(nameof(КУРСЕВРО), dateField, delegate + { + var requestResult = currencyClient.GetExchangeRate(date) + .GetAwaiter() + .GetResult(); + + return requestResult ?? -1m; + }); + + if (result is not decimal) + { + return "Загрузка..."; + } + else + { + exchangeRate = (decimal)result; + var cacheEntryOptions = new MemoryCacheEntryOptions() + .SetSlidingExpiration(TimeSpan.FromHours(1)); + memoryCache.Set(date, exchangeRate, cacheEntryOptions); + } + } if (ExcelAsyncUtil.Run(nameof(РЕХАУЦЕНАРУБ), line, delegate { @@ -163,11 +189,6 @@ public class RhSolutionsFunctions .GetResult() .FirstOrDefault(); - DateTime date = dateField == 0 ? DateTime.Today : DateTime.FromOADate(dateField); - var exchangeRate = currencyClient.GetCurrencyCourse(date) - .GetAwaiter() - .GetResult(); - return product == null ? -1m : product.Price * exchangeRate * 1.2m; }) is not decimal requestResult) @@ -199,7 +220,7 @@ public class RhSolutionsFunctions { var result = ExcelAsyncUtil.Run(nameof(КУРСЕВРО), dateField, delegate { - var requestResult = currencyClient.GetCurrencyCourse(date) + var requestResult = currencyClient.GetExchangeRate(date) .GetAwaiter() .GetResult(); diff --git a/RhSolutions.AddIn/Services/CurrencyClient.cs b/RhSolutions.AddIn/Services/CurrencyClient.cs index 9601ffb..e959bfa 100644 --- a/RhSolutions.AddIn/Services/CurrencyClient.cs +++ b/RhSolutions.AddIn/Services/CurrencyClient.cs @@ -16,7 +16,7 @@ public class CurrencyClient : ICurrencyClient _httpClient = httpClient; } - public async Task GetCurrencyCourse(DateTime date) + public async Task GetExchangeRate(DateTime date) { string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}"; HttpResponseMessage response = await _httpClient.GetAsync(request); diff --git a/RhSolutions.AddIn/Services/ICurrencyClient.cs b/RhSolutions.AddIn/Services/ICurrencyClient.cs index f982a06..22b8760 100644 --- a/RhSolutions.AddIn/Services/ICurrencyClient.cs +++ b/RhSolutions.AddIn/Services/ICurrencyClient.cs @@ -5,5 +5,5 @@ namespace RhSolutions.Services; public interface ICurrencyClient { - public Task GetCurrencyCourse(DateTime date); + public Task GetExchangeRate(DateTime date); }