| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Text; |
| | | 4 | | using System.Xml.Linq; |
| | | 5 | | using Services.ApiServices.ApiSupplierRequestLog; |
| | | 6 | | |
| | | 7 | | namespace Services.ApiServices.MikadoApi; |
| | | 8 | | |
| | | 9 | | /// <summary>SOAP 1.1 транспорт WebService Микадо. Порядок полей и namespace каждой операции взяты из WSDL: |
| | | 10 | | /// ASMX разбирает тело строгой последовательностью, поэтому переставлять параметры нельзя.</summary> |
| | | 11 | | public sealed class MikadoHttpClient |
| | | 12 | | { |
| | | 13 | | private const string Provider = "MikadoMskHod20"; |
| | | 14 | | // service.asmx объявлен без завершающего слэша, а express.asmx/deliveries.asmx и basket.asmx — со слэшем. |
| | | 15 | | private const string ServiceNamespace = "http://mikado-parts.ru/service"; |
| | | 16 | | private const string ExtendedServiceNamespace = "http://mikado-parts.ru/service/"; |
| | | 17 | | private const string BasketNamespace = "http://mikado-parts.ru/ws1/"; |
| | 1 | 18 | | private static readonly XNamespace SoapNamespace = "http://schemas.xmlsoap.org/soap/envelope/"; |
| | 1 | 19 | | private static readonly string[] ClientIdFields = ["ClientID", "nClientID"]; |
| | | 20 | | |
| | | 21 | | private readonly IHttpClientFactory _factory; |
| | | 22 | | private readonly MikadoConfig _config; |
| | | 23 | | private readonly ApiSupplierRequestLogStore? _logs; |
| | | 24 | | |
| | 26 | 25 | | public MikadoHttpClient(IHttpClientFactory factory, MikadoConfig config, ApiSupplierRequestLogStore? logs = null) |
| | 26 | 26 | | => (_factory, _config, _logs) = (factory, config, logs); |
| | | 27 | | |
| | | 28 | | public Task<string> GetMyIpAsync(CancellationToken ct = default) => |
| | 0 | 29 | | SendAsync("service.asmx", "Get_MyIP", ServiceNamespace, [], ct); |
| | | 30 | | |
| | | 31 | | public Task<string> CodeSearchTestAsync(CancellationToken ct = default) => |
| | 2 | 32 | | SendAsync("service.asmx", "Code_Search", ServiceNamespace, |
| | 2 | 33 | | [new("Search_Code", "12345"), ClientId, Password, new("FromStockOnly", "FromStockAndByOrder")], ct); |
| | | 34 | | |
| | | 35 | | public Task<string> CodeInfoTestAsync(string code, CancellationToken ct = default) => |
| | 0 | 36 | | SendAsync("service.asmx", "Code_Info", ServiceNamespace, |
| | 0 | 37 | | [new("ZakazCode", code), ClientId, Password], ct); |
| | | 38 | | |
| | | 39 | | public Task<string> CodeBrandStockInfoAsync(string code, string brand, CancellationToken ct = default) => |
| | 3 | 40 | | SendAsync("service.asmx", "CodeBrandStockInfo", ServiceNamespace, |
| | 3 | 41 | | [new("Code", code), new("Brand", brand), ClientId, Password], ct); |
| | | 42 | | |
| | | 43 | | public Task<string> GetStocksInfoAsync(CancellationToken ct = default) => |
| | 0 | 44 | | SendAsync("service.asmx", "Stocks_Ifo", ServiceNamespace, [ClientId, Password], ct); |
| | | 45 | | |
| | | 46 | | public Task<string> GetBasketAsync(CancellationToken ct = default) => |
| | 5 | 47 | | SendAsync("basket.asmx", "Basket_List", BasketNamespace, [ClientId, Password], ct); |
| | | 48 | | |
| | | 49 | | public Task<string> AddToBasketStrictAsync(string orderCode, int quantity, int deliveryType, string notes, |
| | | 50 | | int expressId, int stockId, CancellationToken ct = default) => |
| | 8 | 51 | | SendAsync("basket.asmx", "Basket_Add_StrictQTY", BasketNamespace, |
| | 8 | 52 | | [new("ZakazCode", orderCode), new("QTY", Number(quantity)), new("DeliveryType", Number(deliveryType)), |
| | 8 | 53 | | new("Notes", notes), ClientId, Password, |
| | 8 | 54 | | new("ExpressID", Number(expressId)), new("StockID", Number(stockId))], ct); |
| | | 55 | | |
| | | 56 | | /// <summary>Судьба позиции корзины: осталась в буфере, ушла в заказ или удалена.</summary> |
| | | 57 | | public Task<string> GetOrderHistoryAsync(long basketItemId, CancellationToken ct = default) => |
| | 3 | 58 | | SendAsync("basket.asmx", "Zakaz_History", BasketNamespace, |
| | 3 | 59 | | [new("nOrderID", basketItemId.ToString(CultureInfo.InvariantCulture))], ct); |
| | | 60 | | |
| | | 61 | | public Task<string> DeleteBasketItemAsync(long itemId, CancellationToken ct = default) => |
| | 2 | 62 | | SendAsync("basket.asmx", "Basket_Delete", BasketNamespace, |
| | 2 | 63 | | [new("ItemID", itemId.ToString(CultureInfo.InvariantCulture)), ClientId, Password], ct); |
| | | 64 | | |
| | | 65 | | /// <summary>Доступные для конкретной позиции варианты экспресс-доставки.</summary> |
| | | 66 | | public Task<string> GetExpressOptionsAsync(string orderCode, int stockId, CancellationToken ct = default) => |
| | 2 | 67 | | SendAsync("express.asmx", "ДоступныеЭкспрессЗаказы", ExtendedServiceNamespace, |
| | 2 | 68 | | [ClientId, new("ZakazCode", orderCode), new("StockID", Number(stockId))], ct); |
| | | 69 | | |
| | | 70 | | public Task<string> GetDeliveriesAsync(DateTime dateFrom, DateTime dateTo, CancellationToken ct = default) => |
| | 2 | 71 | | SendAsync("deliveries.asmx", "Delivery_List", ExtendedServiceNamespace, |
| | 2 | 72 | | [new("Date_From", dateFrom.ToString("O", CultureInfo.InvariantCulture)), |
| | 2 | 73 | | new("Date_To", dateTo.ToString("O", CultureInfo.InvariantCulture)), |
| | 2 | 74 | | new("nClientID", _config.ClientId), Password], ct); |
| | | 75 | | |
| | 22 | 76 | | private KeyValuePair<string, string> ClientId => new("ClientID", _config.ClientId); |
| | 22 | 77 | | private KeyValuePair<string, string> Password => new("Password", _config.Password); |
| | 34 | 78 | | private static string Number(int value) => value.ToString(CultureInfo.InvariantCulture); |
| | | 79 | | |
| | | 80 | | private async Task<string> SendAsync(string endpoint, string operation, string operationNamespace, |
| | | 81 | | IReadOnlyCollection<KeyValuePair<string, string>> fields, CancellationToken ct) |
| | | 82 | | { |
| | 281 | 83 | | foreach (var field in fields) |
| | | 84 | | { |
| | 114 | 85 | | if (!string.IsNullOrWhiteSpace(field.Value)) continue; |
| | 1 | 86 | | if (ClientIdFields.Contains(field.Key) || field.Key == "Password") |
| | 1 | 87 | | throw new MikadoApiException("Не настроены ClientId или Password для Микадо."); |
| | | 88 | | } |
| | | 89 | | |
| | 26 | 90 | | var xml = new XDocument(new XDeclaration("1.0", "utf-8", null), |
| | 26 | 91 | | new XElement(SoapNamespace + "Envelope", |
| | 26 | 92 | | new XElement(SoapNamespace + "Body", |
| | 26 | 93 | | new XElement(XName.Get(operation, operationNamespace), |
| | 135 | 94 | | fields.Select(x => new XElement(XName.Get(x.Key, operationNamespace), x.Value)))))); |
| | 26 | 95 | | var requestXml = xml.ToString(SaveOptions.DisableFormatting); |
| | 26 | 96 | | var action = FormatSoapAction(operationNamespace, operation); |
| | 26 | 97 | | var timer = Stopwatch.StartNew(); |
| | | 98 | | |
| | | 99 | | HttpResponseMessage response; |
| | | 100 | | try |
| | | 101 | | { |
| | 26 | 102 | | using var request = new HttpRequestMessage(HttpMethod.Post, |
| | 26 | 103 | | $"{_config.BaseUrl.TrimEnd('/')}/{endpoint}") |
| | 26 | 104 | | { |
| | 26 | 105 | | Content = new StringContent(requestXml, Encoding.UTF8, "text/xml") |
| | 26 | 106 | | }; |
| | 26 | 107 | | request.Headers.Add("SOAPAction", $"\"{action}\""); |
| | 26 | 108 | | response = await _factory.CreateClient("MikadoMskHod20Api").SendAsync(request, ct); |
| | 26 | 109 | | } |
| | 0 | 110 | | catch (Exception ex) when (ex is not MikadoApiException) |
| | | 111 | | { |
| | 0 | 112 | | _logs?.Add(Provider, HttpMethod.Post.Method, endpoint, null, timer, requestXml, ex.Message); |
| | 0 | 113 | | throw new MikadoApiException("Микадо недоступен.", innerException: ex); |
| | | 114 | | } |
| | | 115 | | |
| | 26 | 116 | | using (response) |
| | | 117 | | { |
| | 26 | 118 | | var responseXml = await response.Content.ReadAsStringAsync(ct); |
| | 26 | 119 | | _logs?.Add(Provider, HttpMethod.Post.Method, endpoint, (int)response.StatusCode, timer, requestXml, response |
| | 26 | 120 | | if (!response.IsSuccessStatusCode) |
| | 0 | 121 | | throw new MikadoApiException($"Микадо вернул HTTP {(int)response.StatusCode}.", (int)response.StatusCode |
| | 26 | 122 | | if (responseXml.Contains("<soap:Fault", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 123 | | throw new MikadoApiException(ReadSoapFault(responseXml)); |
| | 26 | 124 | | return responseXml; |
| | | 125 | | } |
| | 26 | 126 | | } |
| | | 127 | | |
| | | 128 | | private static string ReadSoapFault(string responseXml) |
| | | 129 | | { |
| | | 130 | | try |
| | | 131 | | { |
| | 0 | 132 | | var document = XDocument.Parse(responseXml); |
| | 0 | 133 | | return document.Descendants().FirstOrDefault(x => x.Name.LocalName == "faultstring")?.Value |
| | 0 | 134 | | ?? "Микадо вернул ошибку SOAP."; |
| | | 135 | | } |
| | 0 | 136 | | catch { return "Микадо вернул ошибку SOAP."; } |
| | 0 | 137 | | } |
| | | 138 | | |
| | | 139 | | private static string FormatSoapAction(string operationNamespace, string operation) => |
| | 26 | 140 | | $"{operationNamespace.TrimEnd('/')}/{Uri.EscapeDataString(operation)}"; |
| | | 141 | | } |