| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Xml.Linq; |
| | | 3 | | using Microsoft.Extensions.Caching.Memory; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using Services.ApiServices.InterpartsPriceApi.Models; |
| | | 6 | | |
| | | 7 | | namespace Services.ApiServices.InterpartsPriceApi; |
| | | 8 | | |
| | | 9 | | public class InterpartsPriceApiDataManager |
| | | 10 | | { |
| | | 11 | | private readonly InterpartsPriceApiConfig _config; |
| | | 12 | | private readonly InterpartsPriceApiClient _client; |
| | | 13 | | private readonly IMemoryCache _cache; |
| | | 14 | | private readonly MemoryCacheEntryOptions _cacheOptions; |
| | | 15 | | private readonly ILogger<InterpartsPriceApiDataManager>? _logger; |
| | | 16 | | |
| | 5 | 17 | | public InterpartsPriceApiDataManager( |
| | 5 | 18 | | InterpartsPriceApiConfig config, |
| | 5 | 19 | | InterpartsPriceApiClient client, |
| | 5 | 20 | | IMemoryCache cache, |
| | 5 | 21 | | ILogger<InterpartsPriceApiDataManager>? logger = null) |
| | | 22 | | { |
| | 5 | 23 | | _config = config; |
| | 5 | 24 | | _client = client; |
| | 5 | 25 | | _cache = cache; |
| | 5 | 26 | | _logger = logger; |
| | 5 | 27 | | _cacheOptions = new MemoryCacheEntryOptions() |
| | 5 | 28 | | .SetAbsoluteExpiration(TimeSpan.FromHours(1)) |
| | 5 | 29 | | .SetPriority(CacheItemPriority.Normal); |
| | 5 | 30 | | } |
| | | 31 | | |
| | | 32 | | public async Task<InterpartsPriceSearchResponse> SearchAsync(InterpartsPriceSearchRequest request) |
| | | 33 | | { |
| | 0 | 34 | | if (request == null) |
| | | 35 | | { |
| | 0 | 36 | | return new InterpartsPriceSearchResponse(); |
| | | 37 | | } |
| | | 38 | | |
| | 0 | 39 | | if (string.IsNullOrWhiteSpace(request.Code)) |
| | | 40 | | { |
| | 0 | 41 | | return new InterpartsPriceSearchResponse(); |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | // Кэшируем с учетом параметра useCrosses, т.к. он влияет на итоговую цену. |
| | 0 | 45 | | var normalizedCode = request.Code.Trim(); |
| | 0 | 46 | | var normalizedLogin = string.IsNullOrWhiteSpace(request.Login) ? "admin" : request.Login.Trim().ToLowerInvariant |
| | 0 | 47 | | var cacheKey = |
| | 0 | 48 | | $"InterpartsPrice_Search_{normalizedCode}_{request.ProducerId}_login_{normalizedLogin}_useCrosses_{ToBoolLow |
| | 0 | 49 | | if (_cache.TryGetValue(cacheKey, out InterpartsPriceSearchResponse? cached)) |
| | | 50 | | { |
| | 0 | 51 | | return cached ?? new InterpartsPriceSearchResponse(); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | // Убедимся, что дальше используем нормализованное значение кода |
| | 0 | 55 | | request.Code = normalizedCode; |
| | | 56 | | |
| | 0 | 57 | | var requestUrl = BuildRequestUrl(request); |
| | 0 | 58 | | var httpResult = await _client.GetXmlAsync(requestUrl).ConfigureAwait(false); |
| | 0 | 59 | | var xml = httpResult.Body; |
| | | 60 | | |
| | 0 | 61 | | if (!string.IsNullOrWhiteSpace(httpResult.ErrorMessage) || string.IsNullOrWhiteSpace(xml)) |
| | | 62 | | { |
| | 0 | 63 | | return new InterpartsPriceSearchResponse |
| | 0 | 64 | | { |
| | 0 | 65 | | ErrorMessage = httpResult.ErrorMessage ?? "Interparts Price API вернул пустой ответ.", |
| | 0 | 66 | | HttpStatusCode = httpResult.StatusCode, |
| | 0 | 67 | | RequestUrl = RedactRequestUrl(requestUrl), |
| | 0 | 68 | | RawResponse = xml |
| | 0 | 69 | | }; |
| | | 70 | | } |
| | | 71 | | |
| | | 72 | | try |
| | | 73 | | { |
| | 0 | 74 | | var doc = XDocument.Parse(xml); |
| | 0 | 75 | | var response = new InterpartsPriceSearchResponse(); |
| | | 76 | | |
| | 0 | 77 | | response.SearchProducerId = ParseNullableInt(doc.Descendants("SearchProducerId").FirstOrDefault()?.Value); |
| | | 78 | | |
| | 0 | 79 | | foreach (var priceEl in doc.Descendants("price")) |
| | | 80 | | { |
| | 0 | 81 | | (response.Offers ??= []).Add(ParseOffer(priceEl)); |
| | | 82 | | } |
| | | 83 | | |
| | 0 | 84 | | _cache.Set(cacheKey, response, _cacheOptions); |
| | 0 | 85 | | return response; |
| | | 86 | | } |
| | 0 | 87 | | catch (Exception ex) |
| | | 88 | | { |
| | 0 | 89 | | _logger?.LogError(ex, "Failed to parse InterpartsPriceApi XML"); |
| | 0 | 90 | | return new InterpartsPriceSearchResponse |
| | 0 | 91 | | { |
| | 0 | 92 | | ErrorMessage = $"Ошибка разбора XML Interparts Price API: {ex.Message}", |
| | 0 | 93 | | HttpStatusCode = httpResult.StatusCode, |
| | 0 | 94 | | RequestUrl = RedactRequestUrl(requestUrl), |
| | 0 | 95 | | RawResponse = xml |
| | 0 | 96 | | }; |
| | | 97 | | } |
| | 0 | 98 | | } |
| | | 99 | | |
| | | 100 | | private string BuildRequestUrl(InterpartsPriceSearchRequest request) |
| | | 101 | | { |
| | | 102 | | // price-api.interparts.ru/search.aspx - принимает параметры в querystring |
| | 0 | 103 | | var baseUrl = (_config.BaseUrl ?? "http://price-api.interparts.ru/search.aspx").TrimEnd(); |
| | 0 | 104 | | var separator = baseUrl.Contains("?") ? "&" : "?"; |
| | | 105 | | |
| | 0 | 106 | | var queryPairs = new Dictionary<string, string> |
| | 0 | 107 | | { |
| | 0 | 108 | | ["secret123"] = _config.Secret123, |
| | 0 | 109 | | ["code"] = request.Code ?? "", |
| | 0 | 110 | | ["regionId"] = request.RegionId.ToString(CultureInfo.InvariantCulture), |
| | 0 | 111 | | ["producerId"] = request.ProducerId.ToString(CultureInfo.InvariantCulture), |
| | 0 | 112 | | ["login"] = request.Login ?? "", |
| | 0 | 113 | | ["coef"] = request.Coef.ToString(CultureInfo.InvariantCulture), |
| | 0 | 114 | | ["destCurrencyId"] = request.DestCurrencyId.ToString(CultureInfo.InvariantCulture), |
| | 0 | 115 | | ["useCrosses"] = ToBoolLower(request.UseCrosses), |
| | 0 | 116 | | ["useSets"] = ToBoolLower(request.UseSets), |
| | 0 | 117 | | ["calculateManagerPrice"] = ToBoolLower(request.CalculateManagerPrice), |
| | 0 | 118 | | ["useCrossesSimple"] = ToBoolLower(request.UseCrossesSimple), |
| | 0 | 119 | | }; |
| | | 120 | | |
| | | 121 | | // Uri.EscapeDataString нужен, чтобы корректно экранировать символы в code/login |
| | 0 | 122 | | var query = string.Join("&", |
| | 0 | 123 | | queryPairs.Select(kvp => |
| | 0 | 124 | | $"{kvp.Key}={Uri.EscapeDataString(kvp.Value ?? string.Empty)}")); |
| | | 125 | | |
| | 0 | 126 | | return baseUrl + separator + query; |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | private static string ToBoolLower(bool value) => value ? "true" : "false"; |
| | | 130 | | |
| | | 131 | | private static string RedactRequestUrl(string url) |
| | | 132 | | { |
| | 0 | 133 | | var uri = new Uri(url); |
| | 0 | 134 | | var query = System.Web.HttpUtility.ParseQueryString(uri.Query); |
| | 0 | 135 | | query.Remove("secret123"); |
| | 0 | 136 | | return uri.GetLeftPart(UriPartial.Path) + (query.Count == 0 ? string.Empty : "?" + query); |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | private static InterpartsPriceOffer ParseOffer(XElement priceEl) |
| | | 140 | | { |
| | | 141 | | // Все числовые поля приходят в виде строк (часто с ',' разделителем). |
| | | 142 | | // Для чисел с длинной дробной частью используем double?, чтобы парсинг не "падал" |
| | | 143 | | // из-за ограничений decimal. |
| | 0 | 144 | | return new InterpartsPriceOffer |
| | 0 | 145 | | { |
| | 0 | 146 | | AddAdditionalWeightPrice = ParseNullableBool(GetValue(priceEl, "AddAdditionalWeightPrice")), |
| | 0 | 147 | | Amount = ParseNullableInt(GetValue(priceEl, "Amount")), |
| | 0 | 148 | | ArtNr = GetValue(priceEl, "ArtNr") ?? string.Empty, |
| | 0 | 149 | | |
| | 0 | 150 | | CalculatedPartWeight = ParseNullableDouble(GetValue(priceEl, "CalculatedPartWeight")), |
| | 0 | 151 | | CanBuy = ParseNullableBool(GetValue(priceEl, "CanBuy")), |
| | 0 | 152 | | |
| | 0 | 153 | | ClientPrice = GetValue(priceEl, "ClientPrice") ?? string.Empty, |
| | 0 | 154 | | ClientPriceCalculated = ParseNullableBool(GetValue(priceEl, "ClientPriceCalculated")), |
| | 0 | 155 | | ClientPriceDecimal = ParseNullableDouble(GetValue(priceEl, "ClientPriceDecimal")), |
| | 0 | 156 | | |
| | 0 | 157 | | DbId = ParseNullableInt(GetValue(priceEl, "DbId")), |
| | 0 | 158 | | FixedCoef = ParseNullableDouble(GetValue(priceEl, "FixedCoef")), |
| | 0 | 159 | | HaveImages = ParseNullableBool(GetValue(priceEl, "HaveImages")), |
| | 0 | 160 | | |
| | 0 | 161 | | InPriceSupplier = ParseNullableDouble(GetValue(priceEl, "InPriceSupplier")), |
| | 0 | 162 | | |
| | 0 | 163 | | InputPrice = GetValue(priceEl, "InputPrice") ?? string.Empty, |
| | 0 | 164 | | InputPriceCalculated = ParseNullableBool(GetValue(priceEl, "InputPriceCalculated")), |
| | 0 | 165 | | InputPriceDecimal = ParseNullableDouble(GetValue(priceEl, "InputPriceDecimal")), |
| | 0 | 166 | | |
| | 0 | 167 | | IsPriceActual = ParseNullableBool(GetValue(priceEl, "IsPriceActual")), |
| | 0 | 168 | | |
| | 0 | 169 | | ManagerClientPrice = GetValue(priceEl, "ManagerClientPrice") ?? string.Empty, |
| | 0 | 170 | | ManagerClientPrice2Decimal = ParseNullableDouble(GetValue(priceEl, "ManagerClientPrice2Decimal")), |
| | 0 | 171 | | ManagerClientPriceDecimal = ParseNullableDouble(GetValue(priceEl, "ManagerClientPriceDecimal")), |
| | 0 | 172 | | |
| | 0 | 173 | | ManagerCurrencyId = ParseNullableInt(GetValue(priceEl, "ManagerCurrencyId")), |
| | 0 | 174 | | Multiplicity = ParseNullableInt(GetValue(priceEl, "Multiplicity")), |
| | 0 | 175 | | |
| | 0 | 176 | | OurPrice = GetValue(priceEl, "OurPrice") ?? string.Empty, |
| | 0 | 177 | | OurPrice2 = GetValue(priceEl, "OurPrice2") ?? string.Empty, |
| | 0 | 178 | | OurPrice2Decimal = ParseNullableDouble(GetValue(priceEl, "OurPrice2Decimal")), |
| | 0 | 179 | | |
| | 0 | 180 | | OurPriceCalculated = ParseNullableBool(GetValue(priceEl, "OurPriceCalculated")), |
| | 0 | 181 | | OurPriceCalculated2 = ParseNullableBool(GetValue(priceEl, "OurPriceCalculated2")), |
| | 0 | 182 | | OurPriceDecimal = ParseNullableDouble(GetValue(priceEl, "OurPriceDecimal")), |
| | 0 | 183 | | |
| | 0 | 184 | | Pack = ParseNullableInt(GetValue(priceEl, "Pack")), |
| | 0 | 185 | | |
| | 0 | 186 | | PartCode = GetValue(priceEl, "PartCode") ?? string.Empty, |
| | 0 | 187 | | PartCodeShort = GetValue(priceEl, "PartCodeShort") ?? string.Empty, |
| | 0 | 188 | | PartDescription = GetValue(priceEl, "PartDescription") ?? string.Empty, |
| | 0 | 189 | | |
| | 0 | 190 | | PartRating = ParseNullableInt(GetValue(priceEl, "PartRating")), |
| | 0 | 191 | | PartWeight = ParseNullableDouble(GetValue(priceEl, "PartWeight")), |
| | 0 | 192 | | |
| | 0 | 193 | | PriceForWeight = GetValue(priceEl, "PriceForWeight") ?? string.Empty, |
| | 0 | 194 | | PriceForWeightDecimal = ParseNullableDouble(GetValue(priceEl, "PriceForWeightDecimal")), |
| | 0 | 195 | | PriceForWeightDecimal2 = ParseNullableDouble(GetValue(priceEl, "PriceForWeightDecimal2")), |
| | 0 | 196 | | |
| | 0 | 197 | | PriceId = ParseNullableInt(GetValue(priceEl, "PriceId")), |
| | 0 | 198 | | PriceType = GetValue(priceEl, "PriceType") ?? string.Empty, |
| | 0 | 199 | | |
| | 0 | 200 | | ProducerId = ParseNullableInt(GetValue(priceEl, "ProducerId")), |
| | 0 | 201 | | ProducerMarketPrefix = GetValue(priceEl, "ProducerMarketPrefix") ?? string.Empty, |
| | 0 | 202 | | ProducerName = GetValue(priceEl, "ProducerName") ?? string.Empty, |
| | 0 | 203 | | ProducerPrefix = GetValue(priceEl, "ProducerPrefix") ?? string.Empty, |
| | 0 | 204 | | ProducerRating = ParseNullableInt(GetValue(priceEl, "ProducerRating")), |
| | 0 | 205 | | ProducerTecdocManufacturerId = ParseNullableInt(GetValue(priceEl, "ProducerTecdocManufacturerId")), |
| | 0 | 206 | | ProducerTecdocSupplierId = ParseNullableInt(GetValue(priceEl, "ProducerTecdocSupplierId")), |
| | 0 | 207 | | RealProducerId = ParseNullableInt(GetValue(priceEl, "RealProducerId")), |
| | 0 | 208 | | |
| | 0 | 209 | | SetAmount = ParseNullableInt(GetValue(priceEl, "SetAmount")), |
| | 0 | 210 | | SetCode = GetValue(priceEl, "SetCode") ?? string.Empty, |
| | 0 | 211 | | SetDescription = GetValue(priceEl, "SetDescription") ?? string.Empty, |
| | 0 | 212 | | SetId = ParseNullableInt(GetValue(priceEl, "SetId")), |
| | 0 | 213 | | SetProducerId = ParseNullableInt(GetValue(priceEl, "SetProducerId")), |
| | 0 | 214 | | SetProducerName = GetValue(priceEl, "SetProducerName") ?? string.Empty, |
| | 0 | 215 | | |
| | 0 | 216 | | Source = GetValue(priceEl, "Source") ?? string.Empty, |
| | 0 | 217 | | |
| | 0 | 218 | | SupplierCurrencyId = ParseNullableInt(GetValue(priceEl, "SupplierCurrencyId")), |
| | 0 | 219 | | SupplierExternal = ParseNullableBool(GetValue(priceEl, "SupplierExternal")), |
| | 0 | 220 | | SupplierExtId = GetValue(priceEl, "SupplierExtId") ?? string.Empty, |
| | 0 | 221 | | SupplierId = ParseNullableInt(GetValue(priceEl, "SupplierId")), |
| | 0 | 222 | | SupplierImg = GetValue(priceEl, "SupplierImg") ?? string.Empty, |
| | 0 | 223 | | SupplierName = GetValue(priceEl, "SupplierName") ?? string.Empty, |
| | 0 | 224 | | SupplierPriceVariation = ParseNullableDouble(GetValue(priceEl, "SupplierPriceVariation")), |
| | 0 | 225 | | SupplyTypeExtId = GetValue(priceEl, "SupplyTypeExtId") ?? string.Empty, |
| | 0 | 226 | | SupplyTypeId = ParseNullableInt(GetValue(priceEl, "SupplyTypeId")), |
| | 0 | 227 | | |
| | 0 | 228 | | SurchargeGroup = GetValue(priceEl, "SurchargeGroup") ?? string.Empty, |
| | 0 | 229 | | SurchargeGroupPercent = GetValue(priceEl, "SurchargeGroupPercent") ?? string.Empty, |
| | 0 | 230 | | SurchargeGroupPercentDecimal = ParseNullableDouble(GetValue(priceEl, "SurchargeGroupPercentDecimal")), |
| | 0 | 231 | | |
| | 0 | 232 | | Term = ParseNullableInt(GetValue(priceEl, "Term")), |
| | 0 | 233 | | Time = GetValue(priceEl, "Time") ?? string.Empty, |
| | 0 | 234 | | |
| | 0 | 235 | | UpdatedTime = GetValue(priceEl, "UpdatedTime") ?? string.Empty, |
| | 0 | 236 | | UpdatedTimeSpan = GetValue(priceEl, "UpdatedTimeSpan") ?? string.Empty, |
| | 0 | 237 | | WeightVariation = ParseNullableDouble(GetValue(priceEl, "WeightVariation")), |
| | 0 | 238 | | }; |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | private static string? GetValue(XElement parent, string elementName) => |
| | 0 | 242 | | parent.Element(elementName)?.Value; |
| | | 243 | | |
| | | 244 | | private static int? ParseNullableInt(string? value) |
| | | 245 | | { |
| | 0 | 246 | | if (string.IsNullOrWhiteSpace(value) || value.Trim() == "-") |
| | | 247 | | { |
| | 0 | 248 | | return null; |
| | | 249 | | } |
| | | 250 | | |
| | 0 | 251 | | return int.TryParse(value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) |
| | 0 | 252 | | ? v |
| | 0 | 253 | | : null; |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | private static bool? ParseNullableBool(string? value) |
| | | 257 | | { |
| | 0 | 258 | | if (string.IsNullOrWhiteSpace(value)) |
| | | 259 | | { |
| | 0 | 260 | | return null; |
| | | 261 | | } |
| | | 262 | | |
| | 0 | 263 | | var trimmed = value.Trim(); |
| | 0 | 264 | | if (trimmed == "-") |
| | | 265 | | { |
| | 0 | 266 | | return null; |
| | | 267 | | } |
| | | 268 | | |
| | 0 | 269 | | return bool.TryParse(trimmed, out var v) ? v : null; |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | private static double? ParseNullableDouble(string? value) |
| | | 273 | | { |
| | 0 | 274 | | if (string.IsNullOrWhiteSpace(value) || value.Trim() == "-") |
| | | 275 | | { |
| | 0 | 276 | | return null; |
| | | 277 | | } |
| | | 278 | | |
| | 0 | 279 | | var trimmed = value.Trim(); |
| | | 280 | | |
| | | 281 | | // 1) Пытаемся разобрать по ru-RU (',' как decimal separator) |
| | 0 | 282 | | var ru = CultureInfo.GetCultureInfo("ru-RU"); |
| | 0 | 283 | | if (double.TryParse(trimmed, NumberStyles.Any, ru, out var ruValue)) |
| | | 284 | | { |
| | 0 | 285 | | return ruValue; |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | // 2) Фоллбек: меняем ',' на '.' и парсим как invariant |
| | 0 | 289 | | var invariant = trimmed.Replace(',', '.'); |
| | 0 | 290 | | return double.TryParse(invariant, NumberStyles.Any, CultureInfo.InvariantCulture, out var v) |
| | 0 | 291 | | ? v |
| | 0 | 292 | | : null; |
| | | 293 | | } |
| | | 294 | | } |