From 9ae6a7d0b7ccaa038dcc38c62326d664d4599a22 Mon Sep 17 00:00:00 2001 From: "o.nadymov" Date: Fri, 29 Mar 2024 13:13:54 +0300 Subject: [PATCH] Refactoring: MultiBankProviderFactory & MultiBankProviderBuilder. --- README.md | 56 ++++++++++++-- Spoleto.VirtualKassa.MultiBank.sln | 10 ++- .../Resources => assets}/MainIcon.jpg | Bin src/Directory.Build.props | 70 ++++++++++++++++++ .../MultiBankProviderBuilder.cs | 24 ++++++ .../ServiceCollectionExtensions.cs | 37 +++++++++ ...o.VirtualKassa.MultiBank.Extensions.csproj | 28 +++++++ .../MultiBankProviderFactoryTests.cs | 33 +++++++++ .../MultiBankTests.cs | 6 +- ...poleto.VirtualKassa.MultiBank.Tests.csproj | 21 +++--- .../MainWindow.xaml.cs | 6 +- ...to.VirtualKassa.MultiBank.WpfTester.csproj | 7 +- .../Helpers/HttpHelper.cs | 51 ------------- .../Models/MultiBankOption.cs | 4 +- .../Providers/IMultiBankProvider.cs | 2 +- .../Providers/MultiBankProvider.Invoker.cs | 31 +++++--- .../Providers/MultiBankProvider.cs | 65 ++++++++-------- .../Providers/MultiBankProviderFactory.cs | 32 ++++++++ .../Spoleto.VirtualKassa.MultiBank.csproj | 61 ++------------- 19 files changed, 364 insertions(+), 180 deletions(-) rename {src/Spoleto.VirtualKassa.MultiBank/Resources => assets}/MainIcon.jpg (100%) create mode 100644 src/Directory.Build.props create mode 100644 src/Spoleto.VirtualKassa.MultiBank.Extensions/MultiBankProviderBuilder.cs create mode 100644 src/Spoleto.VirtualKassa.MultiBank.Extensions/ServiceCollectionExtensions.cs create mode 100644 src/Spoleto.VirtualKassa.MultiBank.Extensions/Spoleto.VirtualKassa.MultiBank.Extensions.csproj create mode 100644 src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankProviderFactoryTests.cs delete mode 100644 src/Spoleto.VirtualKassa.MultiBank/Helpers/HttpHelper.cs create mode 100644 src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProviderFactory.cs diff --git a/README.md b/README.md index 300d6b8..97bb740 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ The project for integration with MultiBank host. ## Быстрый старт -Клиент написан на C#, .NET 7.0 с использованием Dependency Injection от [Microsoft](https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage). +Клиент написан на C# .NET 7.0, .NET 8.0 ### Установка Nuget пакета: Для использования этого SDK необходимо установить Nuget пакет ``Spoleto.VirtualKassa.MultiBank``: @@ -20,26 +20,68 @@ https://www.nuget.org/packages/Spoleto.VirtualKassa.MultiBank Install-Package Spoleto.VirtualKassa.MultiBank -ProjectName StoreApplication ``` -### Определение зависимостей +### MultiBankProvider +Для создания экземпляра ``MultiBankProvider`` рекомендуется использовать ``Spoleto.VirtualKassa.MultiBank.MultiBankProviderFactory``: +``` +var factory = new MultiBankProviderFactory(); + +var provider = factory.Build(); + +// Либо с передачей экземпляра HttpClient: +var httpClient = new HttpClient(); +var factory = new MultiBankProviderFactory() + .WithHttpClient(httpClient); + +var provider = factory.Build(); +``` + +### Dependency Injection +Чтобы интегрировать ``Spoleto.VirtualKassa.MultiBank`` в Microsoft Dependency injection следует использовать NuGet пакет [**Spoleto.VirtualKassa.MultiBank.Extensions**](https://www.nuget.org/packages/Spoleto.VirtualKassa.MultiBank.Extensions/). Этот пакет предоставляет методы-расширения для интерфейса ``IServiceCollection``, которые регистрируют ``MultiBankProvider`` как transient сервис. ```csharp using Microsoft.Extensions.DependencyInjection; +using Spoleto.VirtualKassa.MultiBank.Extensions; using Spoleto.VirtualKassa.MultiBank.Models; -using Spoleto.VirtualKassa.MultiBank.Providers; // Set up the dependency injection container -var services = new ServiceCollection(); +var services = new ServiceCollection(); // Register your dependencies here. -services.AddHttpClient(); -services.AddSingleton(); +services.AddMultiBank(); // Build the service provider var serviceProvider = services.BuildServiceProvider(); ``` +### Внедрение службы MultiBankProvider в ваши классы +После регистрации ``Spoleto.VirtualKassa.MultiBank`` в вашем фреймворке Dependency Injection вы можете внедрить ``MultiBankProvider`` в любой класс вашего приложения. + +Для этого внедрите интерфейс ``IMultiBankProvider`` в конструкторы классов, в которых вы хотите использовать функциональность ``MultiBankProvider``: + +```csharp +public class YourMultiBankClass +{ + private readonly ILogger _logger; + private readonly IMultiBankProvider _multiBankProvider; + + public YourMultiBankClass(ILogger logger, IMultiBankProvider multiBankProvider) + { + _logger = logger; + _multiBankProvider = multiBankProvider; + } + + public async Task Sell(SaleSlip slip) + { + var result = await _multiBankProvider.SellAsync(_settings, saleSlip); + + // log the result: + _logger.LogInformation("Sold {slip} with result: {result}", slip, result); + } +} +``` +``` -### Вызов методов API +### Примеры вызовов методов API #### Открытие смены ```csharp var settings = new MultiBankOption { ServiceUrl = "http://localhost:8080/" }; diff --git a/Spoleto.VirtualKassa.MultiBank.sln b/Spoleto.VirtualKassa.MultiBank.sln index f52f74e..6e05c71 100644 --- a/Spoleto.VirtualKassa.MultiBank.sln +++ b/Spoleto.VirtualKassa.MultiBank.sln @@ -8,6 +8,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5AA9A2B7-BD1B-4484-919E-AC10F1616B0D}" ProjectSection(SolutionItems) = preProject src\.editorconfig = src\.editorconfig + src\Directory.Build.props = src\Directory.Build.props LICENSE = LICENSE README.md = README.md EndProjectSection @@ -18,10 +19,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Spoleto.VirtualKassa.MultiB EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WorkFlow", "WorkFlow", "{48E65D95-265B-44DB-A560-CCE813F25732}" ProjectSection(SolutionItems) = preProject + .github\workflows\cd.yml = .github\workflows\cd.yml + .github\workflows\ci.yml = .github\workflows\ci.yml publish-assets-to-github.sh = publish-assets-to-github.sh - .github\workflows\publish-to-nuget.yml = .github\workflows\publish-to-nuget.yml EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spoleto.VirtualKassa.MultiBank.Extensions", "src\Spoleto.VirtualKassa.MultiBank.Extensions\Spoleto.VirtualKassa.MultiBank.Extensions.csproj", "{CF851703-0DB0-47D5-A706-A3DF0398FEAB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -40,6 +44,10 @@ Global {B36D9DEF-7960-42FA-9188-EAFBBEE77C51}.Debug|Any CPU.Build.0 = Debug|Any CPU {B36D9DEF-7960-42FA-9188-EAFBBEE77C51}.Release|Any CPU.ActiveCfg = Release|Any CPU {B36D9DEF-7960-42FA-9188-EAFBBEE77C51}.Release|Any CPU.Build.0 = Release|Any CPU + {CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Spoleto.VirtualKassa.MultiBank/Resources/MainIcon.jpg b/assets/MainIcon.jpg similarity index 100% rename from src/Spoleto.VirtualKassa.MultiBank/Resources/MainIcon.jpg rename to assets/MainIcon.jpg diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 0000000..361cb11 --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,70 @@ + + + + latest + + + + + + true + snupkg + + + + + + true + + + true + + + + + Spoleto.VirtualKassa.MultiBank library + OlegNadymov;Spoleto-Software + SPOLETO Software Development + MainIcon.jpg + https://spoleto.ru + https://github.com/spoleto-software/Spoleto.VirtualKassa.MultiBank + GitHub + README.md + LICENSE + true + МультиКасса; МультиБанк; ВиртуальнаяКасса; VirtualKassa; MultiBank; Multikassa + Copyright © $([System.DateTime]::Now.Year.ToString()) + + 1.13.0 + 1.13.0.0 + 1.13.0.0 + + + + true + $(NoWarn);CS1591 + + + + + True + \ + False + + + True + \ + False + + + True + + False + + + + + + + + diff --git a/src/Spoleto.VirtualKassa.MultiBank.Extensions/MultiBankProviderBuilder.cs b/src/Spoleto.VirtualKassa.MultiBank.Extensions/MultiBankProviderBuilder.cs new file mode 100644 index 0000000..b4ac821 --- /dev/null +++ b/src/Spoleto.VirtualKassa.MultiBank.Extensions/MultiBankProviderBuilder.cs @@ -0,0 +1,24 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Spoleto.VirtualKassa.MultiBank.Extensions +{ + /// + /// Spoleto.VirtualKassa.MultiBank dependency injection builder. + /// + public class MultiBankProviderBuilder + { + /// + /// Creates an instance of . + /// + /// The services collection instance. + internal MultiBankProviderBuilder(IServiceCollection serviceCollection) + { + ServiceCollection = serviceCollection; + } + + /// + /// Gets the service collection. + /// + public IServiceCollection ServiceCollection { get; } + } +} diff --git a/src/Spoleto.VirtualKassa.MultiBank.Extensions/ServiceCollectionExtensions.cs b/src/Spoleto.VirtualKassa.MultiBank.Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..2e7497d --- /dev/null +++ b/src/Spoleto.VirtualKassa.MultiBank.Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Spoleto.VirtualKassa.MultiBank.Extensions +{ + /// + /// Extension methods to configure an for . + /// + public static class ServiceCollectionExtensions + { + /// + /// Adds the Spoleto.VirtualKassa.MultiBank provider. + /// + /// The service collection instance. + /// The instance is provided to support method chaining capabilities. + public static MultiBankProviderBuilder AddMultiBank(this IServiceCollection serviceCollection) + { + serviceCollection.AddHttpClient(); + + // registers the providers on this instance: + return new MultiBankProviderBuilder(serviceCollection); + } + + /// + /// Adds the Spoleto.VirtualKassa.MultiBank provider with the specified instance of . + /// + /// The service collection instance. + /// The instance. + /// The instance is provided to support method chaining capabilities. + public static MultiBankProviderBuilder AddMultiBank(this IServiceCollection serviceCollection, HttpClient httpClient) + { + serviceCollection.AddTransient(x => new MultiBankProvider(httpClient)); + + // registers the providers on this instance: + return new MultiBankProviderBuilder(serviceCollection); + } + } +} \ No newline at end of file diff --git a/src/Spoleto.VirtualKassa.MultiBank.Extensions/Spoleto.VirtualKassa.MultiBank.Extensions.csproj b/src/Spoleto.VirtualKassa.MultiBank.Extensions/Spoleto.VirtualKassa.MultiBank.Extensions.csproj new file mode 100644 index 0000000..d171c71 --- /dev/null +++ b/src/Spoleto.VirtualKassa.MultiBank.Extensions/Spoleto.VirtualKassa.MultiBank.Extensions.csproj @@ -0,0 +1,28 @@ + + + + net7.0;net8.0 + enable + enable + + + + + Spoleto.VirtualKassa.MultiBank extensions for Microsoft DependencyInjection + Spoleto.VirtualKassa.MultiBank.Extensions + МультиКасса; МультиБанк; ВиртуальнаяКасса; VirtualKassa; MultiBank; Multikassa + + Расширения для работы с Microsoft Dependency injection фреймворком для C# SDK для интеграции с хостом Мульти-Банка (Узбекистан) для передачи информации об оплатах покупок. + The extensions for Microsoft Dependency injection framework for the project for integration with MultiBank host. + + + + + + + + + + + + diff --git a/src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankProviderFactoryTests.cs b/src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankProviderFactoryTests.cs new file mode 100644 index 0000000..462bbbe --- /dev/null +++ b/src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankProviderFactoryTests.cs @@ -0,0 +1,33 @@ +namespace Spoleto.VirtualKassa.MultiBank.Tests +{ + public class MultiBankProviderFactoryTests + { + [Test] + public async Task CreateMultiBankProvider() + { + // Arrange + var factory = new MultiBankProviderFactory(); + + // Act + var provider = factory.Build(); + + // Assert + Assert.That(provider, Is.Not.Null); + } + + [Test] + public async Task CreateMultiBankProviderWithHttpClient() + { + // Arrange + var httpClient = new HttpClient(); + var factory = new MultiBankProviderFactory() + .WithHttpClient(httpClient); + + // Act + var provider = factory.Build(); + + // Assert + Assert.That(provider, Is.Not.Null); + } + } +} diff --git a/src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankTests.cs b/src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankTests.cs index ccce4f0..eb22775 100644 --- a/src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankTests.cs +++ b/src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankTests.cs @@ -1,7 +1,6 @@ using Microsoft.Extensions.DependencyInjection; -using Spoleto.Common.Helpers; +using Spoleto.VirtualKassa.MultiBank.Extensions; using Spoleto.VirtualKassa.MultiBank.Models; -using Spoleto.VirtualKassa.MultiBank.Providers; namespace Spoleto.VirtualKassa.MultiBank.Tests { @@ -14,8 +13,7 @@ public class MultiBankTests public void OneTimeSetUp() { var services = new ServiceCollection(); - services.AddHttpClient(); - services.AddSingleton(); + services.AddMultiBank(); _serviceProvider = services.BuildServiceProvider(); diff --git a/src/Spoleto.VirtualKassa.MultiBank.Tests/Spoleto.VirtualKassa.MultiBank.Tests.csproj b/src/Spoleto.VirtualKassa.MultiBank.Tests/Spoleto.VirtualKassa.MultiBank.Tests.csproj index fc56975..11028a1 100644 --- a/src/Spoleto.VirtualKassa.MultiBank.Tests/Spoleto.VirtualKassa.MultiBank.Tests.csproj +++ b/src/Spoleto.VirtualKassa.MultiBank.Tests/Spoleto.VirtualKassa.MultiBank.Tests.csproj @@ -21,26 +21,27 @@ - - - - - - - - + + + + + + + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/src/Spoleto.VirtualKassa.MultiBank.WpfTester/MainWindow.xaml.cs b/src/Spoleto.VirtualKassa.MultiBank.WpfTester/MainWindow.xaml.cs index e475661..e6c1750 100644 --- a/src/Spoleto.VirtualKassa.MultiBank.WpfTester/MainWindow.xaml.cs +++ b/src/Spoleto.VirtualKassa.MultiBank.WpfTester/MainWindow.xaml.cs @@ -3,8 +3,9 @@ using Microsoft.Extensions.DependencyInjection; using Spoleto.Common.Helpers; using Spoleto.VirtualKassa.MultiBank.Models; -using Spoleto.VirtualKassa.MultiBank.Providers; +using Spoleto.VirtualKassa.MultiBank; using Spoleto.VirtualKassa.MultiBank.Tests; +using Spoleto.VirtualKassa.MultiBank.Extensions; namespace Spoleto.VirtualKassa.MultiBank.WpfTester { @@ -24,8 +25,7 @@ public MainWindow() var services = new ServiceCollection(); // Register your dependencies here. - services.AddHttpClient(); - services.AddSingleton(); + services.AddMultiBank(); // Build the service provider _serviceProvider = services.BuildServiceProvider(); diff --git a/src/Spoleto.VirtualKassa.MultiBank.WpfTester/Spoleto.VirtualKassa.MultiBank.WpfTester.csproj b/src/Spoleto.VirtualKassa.MultiBank.WpfTester/Spoleto.VirtualKassa.MultiBank.WpfTester.csproj index 7682fc9..5cb61bf 100644 --- a/src/Spoleto.VirtualKassa.MultiBank.WpfTester/Spoleto.VirtualKassa.MultiBank.WpfTester.csproj +++ b/src/Spoleto.VirtualKassa.MultiBank.WpfTester/Spoleto.VirtualKassa.MultiBank.WpfTester.csproj @@ -27,12 +27,13 @@ - - - + + + + diff --git a/src/Spoleto.VirtualKassa.MultiBank/Helpers/HttpHelper.cs b/src/Spoleto.VirtualKassa.MultiBank/Helpers/HttpHelper.cs deleted file mode 100644 index a7faaf3..0000000 --- a/src/Spoleto.VirtualKassa.MultiBank/Helpers/HttpHelper.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Collections; -using System.Text.Json; -using System.Web; -using Spoleto.Common.Helpers; - -namespace Spoleto.VirtualKassa.MultiBank.Helpers -{ - /// - /// The http helper for creating requests, processing responses. - /// - public class HttpHelper - { - /// - /// Converts to query string. - /// - /// - public static string ToQueryString(T body) - { - var bodyJson = JsonHelper.ToJson(body); - var dictionaryAsObjectValues = JsonHelper.FromJson>(bodyJson); - - var args = new List(); - foreach (var key in dictionaryAsObjectValues.Keys) - { - var jsonValue = (JsonElement)dictionaryAsObjectValues[key]; - var objValue = FlattenJsonValue(jsonValue); - if (objValue is string str) - { - args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(str)}"); - } - else if (objValue is IEnumerable enumerable) - { - foreach (string item in enumerable) - { - args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(item)}"); - } - } - } - - return string.Join("&", args); - } - - private static object? FlattenJsonValue(JsonElement objValue) - => objValue.ValueKind switch - { - JsonValueKind.String => objValue.GetString(), - JsonValueKind.Array => objValue.EnumerateArray().Select(FlattenJsonValue), - _ => objValue.GetRawText() - }; - } -} diff --git a/src/Spoleto.VirtualKassa.MultiBank/Models/MultiBankOption.cs b/src/Spoleto.VirtualKassa.MultiBank/Models/MultiBankOption.cs index c30469c..3f1b499 100644 --- a/src/Spoleto.VirtualKassa.MultiBank/Models/MultiBankOption.cs +++ b/src/Spoleto.VirtualKassa.MultiBank/Models/MultiBankOption.cs @@ -10,6 +10,8 @@ public class MultiBankOption /// public string ServiceUrl { get; init; } - public override string ToString() => ServiceUrl; + public string VersionApi { get; init; } = "v1"; + + public override string ToString() => $"{ServiceUrl} (Version = {VersionApi})."; } } diff --git a/src/Spoleto.VirtualKassa.MultiBank/Providers/IMultiBankProvider.cs b/src/Spoleto.VirtualKassa.MultiBank/Providers/IMultiBankProvider.cs index aacd5d4..f0324da 100644 --- a/src/Spoleto.VirtualKassa.MultiBank/Providers/IMultiBankProvider.cs +++ b/src/Spoleto.VirtualKassa.MultiBank/Providers/IMultiBankProvider.cs @@ -1,6 +1,6 @@ using Spoleto.VirtualKassa.MultiBank.Models; -namespace Spoleto.VirtualKassa.MultiBank.Providers +namespace Spoleto.VirtualKassa.MultiBank { /// /// MultiBank provider. diff --git a/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.Invoker.cs b/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.Invoker.cs index a776c81..03b37fb 100644 --- a/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.Invoker.cs +++ b/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.Invoker.cs @@ -3,28 +3,35 @@ using Spoleto.VirtualKassa.MultiBank.Extensions; using Spoleto.VirtualKassa.MultiBank.Models; -namespace Spoleto.VirtualKassa.MultiBank.Providers +namespace Spoleto.VirtualKassa.MultiBank { public partial class MultiBankProvider { - private readonly IHttpClientFactory _httpClientFactory; - private readonly string _urlPrefix; + private readonly HttpClient _httpClient; /// - /// Constructor. + /// Default constructor. /// - /// - public MultiBankProvider(IHttpClientFactory httpClientFactory) + public MultiBankProvider() + : this(new HttpClient()) { - _httpClientFactory = httpClientFactory; - _urlPrefix = "api/v1/"; //todo: ? } - private async Task InvokeAsync(Uri uri, HttpMethod method, string? requestJsonContent = null, bool throwIfUnsuccess = true, string? bearerToken = null) where T : IMultiBankResponse + /// + /// Creates an instance of . + /// + /// The instance. + public MultiBankProvider(HttpClient httpClient) { - var client = _httpClientFactory.CreateClient(); - client.ConfigureHttpClient(); + if (httpClient is null) + throw new ArgumentNullException(nameof(httpClient)); + _httpClient = httpClient; + _httpClient.ConfigureHttpClient(); + } + + private async Task InvokeAsync(Uri uri, HttpMethod method, string? requestJsonContent = null, bool throwIfUnsuccess = true, string? bearerToken = null) where T : IMultiBankResponse + { using var requestMessage = new HttpRequestMessage(method, uri); InitRequestHeaders(requestMessage); @@ -38,7 +45,7 @@ private async Task InvokeAsync(Uri uri, HttpMethod method, string? request requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); } - using var responseMessage = await client.SendAsync(requestMessage).ConfigureAwait(false); + using var responseMessage = await _httpClient.SendAsync(requestMessage).ConfigureAwait(false); if (responseMessage.IsSuccessStatusCode) { diff --git a/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.cs b/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.cs index e825dc1..36eb053 100644 --- a/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.cs +++ b/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProvider.cs @@ -1,17 +1,18 @@ using Spoleto.Common.Helpers; -using Spoleto.VirtualKassa.MultiBank.Helpers; using Spoleto.VirtualKassa.MultiBank.Models; -namespace Spoleto.VirtualKassa.MultiBank.Providers +namespace Spoleto.VirtualKassa.MultiBank { /// /// MultiBank provider. /// public partial class MultiBankProvider : IMultiBankProvider { + private static string GetUrlPrefix(MultiBankOption settings)=> $"api/{settings.VersionApi}/ "; + public async Task GetDriverConfigurationAsync(MultiBankOption settings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}fiscal/set_up_fm"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}fiscal/set_up_fm"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -20,7 +21,7 @@ public async Task GetDriverConfigurationAsync(MultiBankOpti public async Task GetFiscalModuleInfoAsync(MultiBankOption settings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}info"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}info"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -29,7 +30,7 @@ public async Task GetFiscalModuleInfoAsync(MultiBankOption set public async Task GetFiscalModuleStatusAsync(MultiBankOption settings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}status"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}status"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -38,7 +39,7 @@ public async Task GetFiscalModuleStatusAsync(MultiBankOption public async Task SetCashRegisterSettingsAsync(MultiBankOption settings, CashRegisterSettings cashRegisterSettings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}cashbox"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}cashbox"); var jsonModel = JsonHelper.ToJson(cashRegisterSettings); @@ -49,7 +50,7 @@ public async Task SetCashRegisterSettingsAsync(MultiBankOp public async Task GetCashRegisterSettingsAsync(MultiBankOption settings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}cashbox"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}cashbox"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -58,7 +59,7 @@ public async Task GetCashRegisterSettingsAsync(MultiBankOp public async Task GetCompanyDataAsync(MultiBankOption settings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}contragents"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}contragents"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -67,7 +68,7 @@ public async Task GetCompanyDataAsync(MultiBankOption settings) public async Task GetCashiersAsync(MultiBankOption settings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}cashiers"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}cashiers"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -76,7 +77,7 @@ public async Task GetCashiersAsync(MultiBankOption settings) public async Task CashierLoginAsync(MultiBankOption settings, CashierLoginInfo loginInfo) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}auth/login"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}auth/login"); var jsonModel = JsonHelper.ToJson(loginInfo); @@ -87,7 +88,7 @@ public async Task CashierLoginAsync(MultiBankOption settin public async Task SellAsync(MultiBankOption settings, SaleSlip saleSlip) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(saleSlip); @@ -98,7 +99,7 @@ public async Task SellAsync(MultiBankOption settings, SaleSlip s public async Task ReturnAsync(MultiBankOption settings, ReturnSlip returnSlip) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(returnSlip); @@ -110,7 +111,7 @@ public async Task ReturnAsync(MultiBankOption settings, Return public async Task GetProfilesForAuthorizationAsync(MultiBankOption settings, string bearerToken) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}auth/external/profiles"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}auth/external/profiles"); var result = await InvokeAsync(uri, HttpMethod.Get, bearerToken: bearerToken).ConfigureAwait(false); @@ -119,7 +120,7 @@ public async Task GetProfilesForAuthorizationAsync(MultiBankOpti public async Task AttachProfileToTokenAsync(MultiBankOption settings, string bearerToken, ProfileToAttach profileToAttach) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}auth/external/profiles"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}auth/external/profiles"); var jsonModel = JsonHelper.ToJson(profileToAttach); @@ -130,7 +131,7 @@ public async Task AttachProfileToTokenAsync(MultiBankOpti public async Task GetNomenclatureListAsync(MultiBankOption settings, bool refresh) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products{(refresh ? "?refresh=1" : String.Empty)}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products{(refresh ? "?refresh=1" : String.Empty)}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -139,7 +140,7 @@ public async Task GetNomenclatureListAsync(MultiBankOption se public async Task SendSaleSlipByEmailAsync(MultiBankOption settings, SendMailRequest sendMailRequest) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}sendMail"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}sendMail"); var jsonModel = JsonHelper.ToJson(sendMailRequest); @@ -150,7 +151,7 @@ public async Task SendSaleSlipByEmailAsync(MultiBankOption set public async Task OpenShiftAsync(MultiBankOption settings, OpenShiftRequest openShiftRequest) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(openShiftRequest); @@ -161,7 +162,7 @@ public async Task OpenShiftAsync(MultiBankOption settings, OpenSh public async Task CloseShiftAsync(MultiBankOption settings, CloseShiftRequest closeShiftRequest) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(closeShiftRequest); @@ -172,7 +173,7 @@ public async Task CloseShiftAsync(MultiBankOption settings, Close public async Task XReportAsync(MultiBankOption settings, XReportRequest xReportRequest) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(xReportRequest); @@ -183,7 +184,7 @@ public async Task XReportAsync(MultiBankOption settings, XReportReq public async Task AdvanceSlipAsync(MultiBankOption settings, AdvanceSlip advanceSlip) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(advanceSlip); @@ -195,7 +196,7 @@ public async Task AdvanceSlipAsync(MultiBankOption settings, Ad public async Task AdditionalAdvanceSlipAsync(MultiBankOption settings, AdditionalAdvanceSlip additionalAdvanceSlip) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(additionalAdvanceSlip); @@ -207,7 +208,7 @@ public async Task AdditionalAdvanceSlipAsync(MultiBan public async Task CreditSlipAsync(MultiBankOption settings, CreditSlip creditSlip) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}operations"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}operations"); var jsonModel = JsonHelper.ToJson(creditSlip); @@ -219,7 +220,7 @@ public async Task CreditSlipAsync(MultiBankOption settings, Cred public async Task GetIkpuListAsync(MultiBankOption settings, string parentNode = "root") { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/ikpu_info?node={parentNode}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/ikpu_info?node={parentNode}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -228,7 +229,7 @@ public async Task GetIkpuListAsync(MultiBankOption settings, string p public async Task GetMyIkpuListAsync(MultiBankOption settings) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/myikpu"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/myikpu"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -237,7 +238,7 @@ public async Task GetMyIkpuListAsync(MultiBankOption settings) public async Task AddMyIkpuAsync(MultiBankOption settings, string mxikCode) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/myikpu"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/myikpu"); var jsonModel = JsonHelper.ToJson(new Dictionary { { nameof(mxikCode), mxikCode } }); @@ -248,7 +249,7 @@ public async Task AddMyIkpuAsync(MultiBankOption settings, st public async Task RemoveMyIkpuAsync(MultiBankOption settings, string mxikCode) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/myikpu"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/myikpu"); var jsonModel = JsonHelper.ToJson(new Dictionary { { nameof(mxikCode), mxikCode } }); @@ -258,7 +259,7 @@ public async Task RemoveMyIkpuAsync(MultiBankOption settings, string mxikCode) public async Task FindIkpuListAsync(MultiBankOption settings, IkpuTextFilter ikpuTextFilter) { var queryString = HttpHelper.ToQueryString(ikpuTextFilter); - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/by_params?{queryString}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/by_params?{queryString}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -268,7 +269,7 @@ public async Task FindIkpuListAsync(MultiBankOption settings, public async Task FindIkpuListAsync(MultiBankOption settings, IkpuCodeFilter ikpuCodeFilter) { var queryString = HttpHelper.ToQueryString(ikpuCodeFilter); - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/by_params?{queryString}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/by_params?{queryString}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -278,7 +279,7 @@ public async Task FindIkpuListAsync(MultiBankOption settings, public async Task FindIkpuListAsync(MultiBankOption settings, IkpuGtinFilter ikpuGtinFilter) { var queryString = HttpHelper.ToQueryString(ikpuGtinFilter); - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/by_params?{queryString}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/by_params?{queryString}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -287,7 +288,7 @@ public async Task FindIkpuListAsync(MultiBankOption settings, public async Task GetIkpuChangeHistoryAsync(MultiBankOption settings, string catalogCode) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/ikpu_history?catalogCode={catalogCode}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/ikpu_history?catalogCode={catalogCode}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -296,7 +297,7 @@ public async Task GetIkpuChangeHistoryAsync(MultiBankOption s public async Task CheckIkpuAsync(MultiBankOption settings, string mxikCode) { - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}products/check?mxikCode={mxikCode}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}products/check?mxikCode={mxikCode}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); @@ -306,7 +307,7 @@ public async Task CheckIkpuAsync(MultiBankOption settings, string public async Task GetSlipListAsync(MultiBankOption settings, SlipCriteria slipCriteria) { var queryString = HttpHelper.ToQueryString(slipCriteria); - var uri = new Uri(new Uri(settings.ServiceUrl), $"{_urlPrefix}receipts?{queryString}"); + var uri = new Uri(new Uri(settings.ServiceUrl), $"{GetUrlPrefix(settings)}receipts?{queryString}"); var result = await InvokeAsync(uri, HttpMethod.Get).ConfigureAwait(false); diff --git a/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProviderFactory.cs b/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProviderFactory.cs new file mode 100644 index 0000000..934cb37 --- /dev/null +++ b/src/Spoleto.VirtualKassa.MultiBank/Providers/MultiBankProviderFactory.cs @@ -0,0 +1,32 @@ +namespace Spoleto.VirtualKassa.MultiBank +{ + /// + /// The MultiBankProvider factory used to create an instance of . + /// + public class MultiBankProviderFactory + { + private HttpClient? _httpClient; + + /// + /// Sets the HttpClient of the MultiBankProvider. + /// + /// The instance. + /// The instance is provided to support method chaining capabilities. + /// Thrown when is null. + public MultiBankProviderFactory WithHttpClient(HttpClient httpClient) + { + if (httpClient is null) + throw new ArgumentNullException(nameof(httpClient)); + + _httpClient = httpClient; + + return this; + } + + /// + /// Creates the MultiBankProvider instance. + /// + /// Instance of . + public IMultiBankProvider Build() => _httpClient == null ? new MultiBankProvider() : new MultiBankProvider(_httpClient); + } +} diff --git a/src/Spoleto.VirtualKassa.MultiBank/Spoleto.VirtualKassa.MultiBank.csproj b/src/Spoleto.VirtualKassa.MultiBank/Spoleto.VirtualKassa.MultiBank.csproj index 6d46bfc..56b29b5 100644 --- a/src/Spoleto.VirtualKassa.MultiBank/Spoleto.VirtualKassa.MultiBank.csproj +++ b/src/Spoleto.VirtualKassa.MultiBank/Spoleto.VirtualKassa.MultiBank.csproj @@ -1,74 +1,25 @@  - net7.0 + net7.0;net8.0 enable enable - Spoleto.VirtualKassa.MultiBank - Spoleto.VirtualKassa.MultiBank - Spoleto.VirtualKassa.MultiBank - false - bin\$(Configuration)\$(AssemblyName).xml - True - preview - - - - - - true - snupkg - True - - - - - - true - - - true - Spoleto.VirtualKassa.MultiBank library + Spoleto.VirtualKassa.MultiBank + Spoleto.VirtualKassa.MultiBank + МультиКасса; МультиБанк; ВиртуальнаяКасса; VirtualKassa; MultiBank; Multikassa C# SDK для интеграции с хостом Мульти-Банка (Узбекистан) для передачи информации об оплатах покупок. The project for integration with MultiBank host. - Spoleto.VirtualKassa.MultiBank - OlegNadymov;Spoleto-Software - SPOLETO Software Development - MainIcon.jpg - https://spoleto.ru - https://github.com/spoleto-software/Spoleto.VirtualKassa.MultiBank - git - MIT - МультиКасса; МультиБанк; ВиртуальнаяКасса; MultiBank; Multikassa; - Copyright © $([System.DateTime]::Now.Year.ToString()) - - $([System.DateTime]::Now.AddYears(-2022).Year.ToString()).$([System.DateTime]::Now.ToString("MM.dd.HHmm")) - $([System.DateTime]::Now.AddYears(-2022).Year.ToString()).$([System.DateTime]::Now.ToString("MM.dd.HHmm")) - $([System.DateTime]::Now.AddYears(-2022).Year.ToString()).$([System.DateTime]::Now.ToString("MM.dd.HHmm")) - README.md - - True - \ - - - True - - - - - - - - + +