| | | 1 | | using Microsoft.AspNetCore.Authorization; |
| | | 2 | | using Microsoft.AspNetCore.Mvc; |
| | | 3 | | using Microsoft.Extensions.Caching.Memory; |
| | | 4 | | using Services.ApiServices.ArmtekApi; |
| | | 5 | | using Services.ApiServices.ArmtekApi.Models.Envelope; |
| | | 6 | | using Services.ApiServices.ArmtekApi.Models.Response; |
| | | 7 | | using Services.ApiServices.TradesoftApi.Models.Response; |
| | | 8 | | using Services.ApiSupplierSettingsServices; |
| | | 9 | | using Services.PriceСlculationServices; |
| | | 10 | | using OzonDomains; |
| | | 11 | | using OzonDomains.Models; |
| | | 12 | | using OzonOrdersWeb.Areas.Studio2.ViewModels; |
| | | 13 | | using OzonOrdersWeb.Filters; |
| | | 14 | | |
| | | 15 | | namespace OzonOrdersWeb.Areas.Studio2.Controllers; |
| | | 16 | | |
| | | 17 | | [Area("Studio2")] |
| | | 18 | | [Authorize(Roles = "User,Admin")] |
| | | 19 | | [ServiceFilter(typeof(SupplierQuotationHistoryFilter), Order = 0)] |
| | | 20 | | [ServiceFilter(typeof(SupplierDeliverySurchargeFilter), Order = 1)] |
| | | 21 | | [ServiceFilter(typeof(SupplierWarehouseRestrictionFilter), Order = 2)] |
| | | 22 | | public class ArmtekPriceController : Controller |
| | | 23 | | { |
| | | 24 | | protected readonly ArmtekDataManager ArmtekDataManager; |
| | | 25 | | protected readonly ApiSupplierSettingsService SettingsService; |
| | | 26 | | protected readonly ICurrencyRateFetcher CurrencyRateFetcher; |
| | | 27 | | private readonly IMemoryCache _cache; |
| | | 28 | | private readonly ArmtekDeliveryAddressMappingService _deliveryAddressMappings; |
| | | 29 | | private readonly ArmtekStoreDirectory _storeDirectory; |
| | | 30 | | |
| | 10 | 31 | | public ArmtekPriceController(ArmtekDataManager armtekDataManager, |
| | 10 | 32 | | ApiSupplierSettingsService settingsService, |
| | 10 | 33 | | ICurrencyRateFetcher currencyRateFetcher, |
| | 10 | 34 | | IMemoryCache cache, |
| | 10 | 35 | | ArmtekDeliveryAddressMappingService deliveryAddressMappings, |
| | 10 | 36 | | ArmtekStoreDirectory storeDirectory) |
| | | 37 | | { |
| | 10 | 38 | | ArmtekDataManager = armtekDataManager; |
| | 10 | 39 | | SettingsService = settingsService; |
| | 10 | 40 | | CurrencyRateFetcher = currencyRateFetcher; |
| | 10 | 41 | | _cache = cache; |
| | 10 | 42 | | _deliveryAddressMappings = deliveryAddressMappings; |
| | 10 | 43 | | _storeDirectory = storeDirectory; |
| | 10 | 44 | | } |
| | | 45 | | |
| | 0 | 46 | | protected virtual string ProviderDisplayName => "Армтек"; |
| | 13 | 47 | | protected virtual string ProviderCacheKey => "Armtek"; |
| | | 48 | | |
| | | 49 | | protected virtual Task<ApiSupplierSettings> GetSettingsAsync(CancellationToken cancellationToken) |
| | 7 | 50 | | => SettingsService.GetArmtekAsync(cancellationToken); |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// Прогревает соединение и справочники Армтека до первого поиска товара. |
| | | 54 | | /// Поиск артикула намеренно не выполняется: он остаётся точным и актуальным на момент раскрытия строки. |
| | | 55 | | /// </summary> |
| | | 56 | | [HttpGet] |
| | | 57 | | public async Task<IActionResult> Warmup(string? vkorg = null) |
| | | 58 | | { |
| | | 59 | | try |
| | | 60 | | { |
| | 6 | 61 | | var settings = await GetSettingsAsync(HttpContext.RequestAborted); |
| | 5 | 62 | | if (!settings.IsQuotationEnabled) |
| | 1 | 63 | | return NoContent(); |
| | | 64 | | |
| | 4 | 65 | | ResolveStoreNamesByKeyzak(vkorg); |
| | 4 | 66 | | await GetUserInfoAsync(vkorg); |
| | | 67 | | |
| | 0 | 68 | | return NoContent(); |
| | | 69 | | } |
| | 2 | 70 | | catch (ArmtekApiException) |
| | | 71 | | { |
| | | 72 | | // Прогрев опционален: при ошибке внешнего API поставщика отдаём 204 NoContent, |
| | | 73 | | // чтобы не порождать ложных сбоев на клиенте и в логах. |
| | 2 | 74 | | return NoContent(); |
| | | 75 | | } |
| | 1 | 76 | | catch (HttpRequestException) |
| | | 77 | | { |
| | | 78 | | // Временный сетевой сбой внешнего поставщика при фоновом прогреве не ломает страницу. |
| | 1 | 79 | | return NoContent(); |
| | | 80 | | } |
| | 2 | 81 | | catch (OperationCanceledException) when (HttpContext.RequestAborted.IsCancellationRequested) |
| | | 82 | | { |
| | | 83 | | // Прокси или браузер закрыл соединение до ответа; это не ошибка приложения. |
| | 1 | 84 | | return StatusCode(499, new { error = "request_canceled" }); |
| | | 85 | | } |
| | 1 | 86 | | catch (OperationCanceledException) |
| | | 87 | | { |
| | | 88 | | // Таймаут обращения к внешнему сервису поставщика во время прогрева. |
| | 1 | 89 | | return NoContent(); |
| | | 90 | | } |
| | 6 | 91 | | } |
| | | 92 | | |
| | | 93 | | [HttpGet] |
| | | 94 | | public async Task<IActionResult> Search(string code, string? brand, int? orderId = null, string? vkorg = null, |
| | | 95 | | bool includeAnalogs = false, string? zasylWarehouseName = null) |
| | | 96 | | { |
| | | 97 | | try |
| | | 98 | | { |
| | 4 | 99 | | if (string.IsNullOrWhiteSpace(code)) |
| | 3 | 100 | | return Ok(new ArmtekQuotationResponse([], null)); |
| | | 101 | | |
| | 1 | 102 | | var settings = await GetSettingsAsync(HttpContext.RequestAborted); |
| | 1 | 103 | | if (!settings.IsQuotationEnabled) |
| | 0 | 104 | | return Ok(new ArmtekQuotationResponse([], null)); |
| | | 105 | | |
| | | 106 | | |
| | 1 | 107 | | var article = code.Trim(); |
| | 1 | 108 | | var producer = string.IsNullOrWhiteSpace(brand) ? null : brand.Trim(); |
| | 1 | 109 | | var searchInput = await ResolveAssortmentSearchInputAsync(article, producer, vkorg); |
| | | 110 | | |
| | 1 | 111 | | var userInfo = await GetUserInfoAsync(vkorg); |
| | 0 | 112 | | if (userInfo.HasErrors) |
| | 0 | 113 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = BuildArmtekErrorMessage(userInfo.Messages) |
| | | 114 | | |
| | 0 | 115 | | var warehouse = await _deliveryAddressMappings.ResolveWarehouseAsync(orderId, zasylWarehouseName, HttpContex |
| | 0 | 116 | | var deliveryMapping = await _deliveryAddressMappings.ResolveAsync(ProviderCacheKey, orderId, zasylWarehouseN |
| | 0 | 117 | | var kunnrRg = deliveryMapping?.BuyerKunnr ?? ResolveKunnrRg(userInfo.Resp); |
| | 0 | 118 | | if (string.IsNullOrWhiteSpace(kunnrRg)) |
| | 0 | 119 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = "Армтек getUserInfo не вернул ни одного KUN |
| | | 120 | | |
| | 0 | 121 | | var queryType = includeAnalogs ? 2 : 1; |
| | | 122 | | |
| | | 123 | | // Справочник складов грузится в фоне при старте приложения; проценка его не ждёт. |
| | 0 | 124 | | var storeNameByKeyzak = ResolveStoreNamesByKeyzak(vkorg); |
| | 0 | 125 | | var searchResponse = await GetSearchResponseAsync( |
| | 0 | 126 | | kunnrRg: kunnrRg, |
| | 0 | 127 | | pin: searchInput.Pin, |
| | 0 | 128 | | brand: searchInput.Brand, |
| | 0 | 129 | | vkorg: vkorg, |
| | 0 | 130 | | queryType: queryType, |
| | 0 | 131 | | kunnrZa: deliveryMapping?.DeliveryAddressKunnr, |
| | 0 | 132 | | incotermsSelfPickup: deliveryMapping is null ? null : false); |
| | | 133 | | |
| | 0 | 134 | | if (searchResponse.HasErrors) |
| | 0 | 135 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = BuildArmtekErrorMessage(searchResponse.Mess |
| | | 136 | | |
| | 0 | 137 | | var items = new List<PreOrderItem>(); |
| | 0 | 138 | | foreach (var offer in searchResponse.Resp ?? new List<ArmtekSearchItem>()) |
| | | 139 | | { |
| | 0 | 140 | | var sourceCurrency = ResolveCurrency(offer.Currency, CurrencyCode.RUB); |
| | 0 | 141 | | var rateToRub = await GetRateToRubAsync(sourceCurrency); |
| | 0 | 142 | | var item = MapToPreOrderItem(offer, storeNameByKeyzak, rateToRub, sourceCurrency, |
| | 0 | 143 | | settings.SupplierId, settings.Supplier?.CurrencyCode, ProviderDisplayName); |
| | 0 | 144 | | if (item != null) |
| | | 145 | | { |
| | 0 | 146 | | AddDeliveryMappingMetadata(item, deliveryMapping, userInfo.Resp, settings.DeliveryAddress); |
| | 0 | 147 | | items.Add(item); |
| | | 148 | | } |
| | 0 | 149 | | } |
| | | 150 | | |
| | 0 | 151 | | var warning = orderId.HasValue && deliveryMapping is null |
| | 0 | 152 | | ? warehouse.IsUnknownZasyl |
| | 0 | 153 | | ? $"Засыл «{warehouse.WarehouseName}» не найден среди складов Studio2. Проценка Armtek выполнена с н |
| | 0 | 154 | | : "Адрес доставки Armtek не связан с эффективным складом заказа. Проценка выполнена с настройками Ar |
| | 0 | 155 | | : null; |
| | 0 | 156 | | var settingsUrl = warning is null ? null : Url.Action( |
| | 0 | 157 | | ProviderCacheKey == ApiSupplierSettings.ArmtekByProviderKey ? "ArmtekBy" : "Armtek", |
| | 0 | 158 | | "ApiSupplierSettings", new { area = "Studio2" }) + |
| | 0 | 159 | | (warehouse.WarehouseId.HasValue ? $"#armtek-mapping-{warehouse.WarehouseId.Value}" : string.Empty); |
| | 0 | 160 | | return Ok(new ArmtekQuotationResponse(items, warning, settingsUrl)); |
| | | 161 | | } |
| | 1 | 162 | | catch (ArmtekApiException ex) |
| | | 163 | | { |
| | 1 | 164 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = ex.Message }); |
| | | 165 | | } |
| | 0 | 166 | | catch (HttpRequestException) |
| | | 167 | | { |
| | 0 | 168 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = "Армтек временно разорвал соединение. Повторите |
| | | 169 | | } |
| | 0 | 170 | | catch (Exception ex) when (ex is TimeoutException or TaskCanceledException) |
| | | 171 | | { |
| | 0 | 172 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = "Истекло время ожидания ответа от Армтек." }); |
| | | 173 | | } |
| | 4 | 174 | | } |
| | | 175 | | |
| | | 176 | | private static string ResolveKunnrRg(ArmtekUserInfoResponse? userInfo) |
| | | 177 | | { |
| | 0 | 178 | | var buyers = userInfo?.Structure?.RgTab ?? new List<ArmtekBuyerItem>(); |
| | 0 | 179 | | var preferred = buyers.FirstOrDefault(x => x.Default == 1); |
| | 0 | 180 | | if (!string.IsNullOrWhiteSpace(preferred?.Kunnr)) |
| | 0 | 181 | | return preferred.Kunnr; |
| | | 182 | | |
| | 0 | 183 | | return buyers.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.Kunnr))?.Kunnr ?? string.Empty; |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | private void AddDeliveryMappingMetadata(PreOrderItem item, ArmtekDeliveryAddressSelection? mapping, |
| | | 187 | | ArmtekUserInfoResponse? userInfo, string? configuredDeliveryAddress) |
| | | 188 | | { |
| | 0 | 189 | | item.ProviderData ??= new Dictionary<string, string?>(); |
| | 0 | 190 | | item.ProviderData["deliveryMappingLinked"] = mapping is null ? "false" : "true"; |
| | 0 | 191 | | if (mapping is null) |
| | | 192 | | { |
| | 0 | 193 | | if (!string.IsNullOrWhiteSpace(configuredDeliveryAddress)) |
| | 0 | 194 | | item.ProviderData["deliveryDestination"] = configuredDeliveryAddress.Trim(); |
| | 0 | 195 | | return; |
| | | 196 | | } |
| | | 197 | | |
| | 0 | 198 | | var buyer = userInfo?.Structure.RgTab.FirstOrDefault(x => x.Kunnr == mapping.BuyerKunnr); |
| | 0 | 199 | | var address = buyer?.ZaTab.FirstOrDefault(x => x.Kunnr == mapping.DeliveryAddressKunnr); |
| | 0 | 200 | | var addressName = address is null |
| | 0 | 201 | | ? mapping.DeliveryAddressKunnr |
| | 0 | 202 | | : string.Join("; ", new[] { address.ShortName, address.Address }.Where(x => !string.IsNullOrWhiteSpace(x))); |
| | 0 | 203 | | item.ProviderData["deliveryMappingAddress"] = addressName; |
| | 0 | 204 | | item.ProviderData["deliveryDestination"] = configuredDeliveryAddress ?? addressName; |
| | | 205 | | // Корзина в окне проведения показывает ту же пару «клиент + адрес», что и страница /SupplierCart. |
| | 0 | 206 | | item.ProviderData["deliveryMappingBuyerKunnr"] = mapping.BuyerKunnr; |
| | 0 | 207 | | item.ProviderData["deliveryMappingBuyerName"] = buyer is null |
| | 0 | 208 | | ? null |
| | 0 | 209 | | : (string.IsNullOrWhiteSpace(buyer.ShortName) ? buyer.FullName : buyer.ShortName); |
| | 0 | 210 | | item.ProviderData["deliveryMappingAddressKunnr"] = mapping.DeliveryAddressKunnr; |
| | 0 | 211 | | item.ProviderData["deliveryMappingSettingsUrl"] = Url.Action( |
| | 0 | 212 | | ProviderCacheKey == ApiSupplierSettings.ArmtekByProviderKey ? "ArmtekBy" : "Armtek", |
| | 0 | 213 | | "ApiSupplierSettings", new { area = "Studio2" }) + $"#armtek-mapping-{mapping.ShipmentWarehouseId}"; |
| | 0 | 214 | | } |
| | | 215 | | |
| | | 216 | | private static string BuildArmtekErrorMessage(IEnumerable<Services.ApiServices.ArmtekApi.Models.Envelope.ArmtekMessa |
| | | 217 | | { |
| | 0 | 218 | | var list = (messages ?? Enumerable.Empty<Services.ApiServices.ArmtekApi.Models.Envelope.ArmtekMessage>()) |
| | 0 | 219 | | .Select(m => m?.Text?.Trim()) |
| | 0 | 220 | | .Where(t => !string.IsNullOrWhiteSpace(t)) |
| | 0 | 221 | | .ToList(); |
| | | 222 | | |
| | 0 | 223 | | return list.Count > 0 |
| | 0 | 224 | | ? string.Join("; ", list) |
| | 0 | 225 | | : "Армтек вернул ошибку без текста в MESSAGES."; |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | private IReadOnlyDictionary<string, string> ResolveStoreNamesByKeyzak(string? vkorg) |
| | | 229 | | { |
| | 4 | 230 | | if (_storeDirectory.TryGet(ProviderCacheKey, vkorg, out var stores)) |
| | 0 | 231 | | return stores; |
| | | 232 | | |
| | | 233 | | // Справочник ещё не загружен: подпись склада будет кодом KEYZAK, загрузка идёт в фоне. |
| | 4 | 234 | | _storeDirectory.RequestLoad(ProviderCacheKey, vkorg); |
| | 4 | 235 | | return stores; |
| | | 236 | | } |
| | | 237 | | |
| | | 238 | | private async Task<Services.ApiServices.ArmtekApi.Models.Envelope.ArmtekResponse<ArmtekUserInfoResponse>> GetUserInf |
| | | 239 | | { |
| | 5 | 240 | | var cacheKey = $"api-supplier:{ProviderCacheKey}:user-info:{ResolveVkorgCachePart(vkorg)}"; |
| | 5 | 241 | | if (_cache.TryGetValue(cacheKey, out Services.ApiServices.ArmtekApi.Models.Envelope.ArmtekResponse<ArmtekUserInf |
| | 0 | 242 | | return cachedUserInfo; |
| | | 243 | | |
| | 5 | 244 | | var userInfo = await ArmtekDataManager.GetUserInfoAsync(vkorg: vkorg, structure: true, ct: HttpContext.RequestAb |
| | 0 | 245 | | if (!userInfo.HasErrors) |
| | 0 | 246 | | _cache.Set(cacheKey, userInfo, TimeSpan.FromMinutes(5)); |
| | 0 | 247 | | return userInfo; |
| | 0 | 248 | | } |
| | | 249 | | |
| | | 250 | | /// <summary> |
| | | 251 | | /// Portal Armtek умеет нормализовать артикул (например AP1086 → AP 108/6), а ws_search/search — нет всегда. |
| | | 252 | | /// Поэтому перед проценкой подбираем каноническую пару PIN/BRAND через ассортимент, не смешивая бренды-аналогии. |
| | | 253 | | /// </summary> |
| | | 254 | | private async Task<ArmtekSearchInput> ResolveAssortmentSearchInputAsync(string article, string? producer, string? vk |
| | | 255 | | { |
| | 1 | 256 | | if (string.IsNullOrWhiteSpace(producer)) |
| | 1 | 257 | | return new ArmtekSearchInput(article, producer); |
| | | 258 | | |
| | 0 | 259 | | var cacheKey = $"api-supplier:{ProviderCacheKey}:assortment:{ResolveVkorgCachePart(vkorg)}:{NormalizeForMatch(ar |
| | 0 | 260 | | if (_cache.TryGetValue(cacheKey, out ArmtekSearchInput? cached) && cached is not null) |
| | 0 | 261 | | return cached; |
| | | 262 | | |
| | | 263 | | try |
| | | 264 | | { |
| | 0 | 265 | | var apiBrand = await ArmtekDataManager.ResolveBrandAsync(producer, HttpContext.RequestAborted); |
| | 0 | 266 | | var response = await ArmtekDataManager.AssortmentSearchAsync(article, vkorg, ct: HttpContext.RequestAborted) |
| | 0 | 267 | | if (response.HasErrors || response.Resp is null) |
| | 0 | 268 | | return new ArmtekSearchInput(article, producer); |
| | | 269 | | |
| | 0 | 270 | | var candidate = response.Resp.FirstOrDefault(item => |
| | 0 | 271 | | !string.IsNullOrWhiteSpace(item.Pin) && |
| | 0 | 272 | | !string.IsNullOrWhiteSpace(item.Brand) && |
| | 0 | 273 | | (string.Equals(NormalizeForMatch(item.Brand), NormalizeForMatch(apiBrand), StringComparison.Ordinal) || |
| | 0 | 274 | | string.Equals(NormalizeForMatch(item.Brand), NormalizeForMatch(producer), StringComparison.Ordinal))); |
| | 0 | 275 | | if (candidate is null) |
| | 0 | 276 | | return new ArmtekSearchInput(article, producer); |
| | | 277 | | |
| | 0 | 278 | | var resolved = new ArmtekSearchInput(candidate.Pin.Trim(), candidate.Brand.Trim()); |
| | 0 | 279 | | _cache.Set(cacheKey, resolved, TimeSpan.FromMinutes(5)); |
| | 0 | 280 | | return resolved; |
| | | 281 | | } |
| | 0 | 282 | | catch (Exception ex) when (ex is ArmtekApiException or HttpRequestException or TaskCanceledException) |
| | | 283 | | { |
| | | 284 | | // Ассортимент — вспомогательная нормализация. При его недоступности сохраняем прежнюю проценку. |
| | 0 | 285 | | return new ArmtekSearchInput(article, producer); |
| | | 286 | | } |
| | 1 | 287 | | } |
| | | 288 | | |
| | | 289 | | private async Task<Services.ApiServices.ArmtekApi.Models.Envelope.ArmtekResponse<List<ArmtekSearchItem>>> GetSearchR |
| | | 290 | | string kunnrRg, |
| | | 291 | | string pin, |
| | | 292 | | string? brand, |
| | | 293 | | string? vkorg, |
| | | 294 | | int queryType, |
| | | 295 | | string? kunnrZa, |
| | | 296 | | bool? incotermsSelfPickup) |
| | | 297 | | { |
| | 0 | 298 | | var cacheKey = $"api-supplier:{ProviderCacheKey}:quotation:{ResolveVkorgCachePart(vkorg)}:{kunnrRg}:{pin.Trim(). |
| | 0 | 299 | | if (_cache.TryGetValue(cacheKey, out Services.ApiServices.ArmtekApi.Models.Envelope.ArmtekResponse<List<ArmtekSe |
| | 0 | 300 | | return cachedSearch; |
| | | 301 | | |
| | 0 | 302 | | var searchResponse = await ArmtekDataManager.SearchAsync( |
| | 0 | 303 | | kunnrRg: kunnrRg, |
| | 0 | 304 | | pin: pin, |
| | 0 | 305 | | brand: brand, |
| | 0 | 306 | | vkorg: vkorg, |
| | 0 | 307 | | queryType: queryType, |
| | 0 | 308 | | kunnrZa: kunnrZa, |
| | 0 | 309 | | incotermsSelfPickup: incotermsSelfPickup, |
| | 0 | 310 | | ct: HttpContext.RequestAborted); |
| | | 311 | | |
| | | 312 | | // Цена быстро меняется, поэтому держим только короткий кэш. Ошибки и частичные ответы не кэшируем. |
| | 0 | 313 | | if (!searchResponse.HasErrors) |
| | 0 | 314 | | _cache.Set(cacheKey, searchResponse, TimeSpan.FromMinutes(1)); |
| | 0 | 315 | | return searchResponse; |
| | 0 | 316 | | } |
| | | 317 | | |
| | 5 | 318 | | private static string ResolveVkorgCachePart(string? vkorg) => string.IsNullOrWhiteSpace(vkorg) ? "default" : vkorg.T |
| | | 319 | | |
| | 0 | 320 | | private static string NormalizeForMatch(string? value) => new((value ?? string.Empty) |
| | 0 | 321 | | .Where(char.IsLetterOrDigit) |
| | 0 | 322 | | .Select(char.ToUpperInvariant) |
| | 0 | 323 | | .ToArray()); |
| | | 324 | | |
| | 1 | 325 | | private sealed record ArmtekSearchInput(string Pin, string? Brand); |
| | | 326 | | |
| | | 327 | | private static PreOrderItem? MapToPreOrderItem( |
| | | 328 | | ArmtekSearchItem? offer, |
| | | 329 | | IReadOnlyDictionary<string, string> storeNameByKeyzak, |
| | | 330 | | decimal rateToRub, |
| | | 331 | | CurrencyCode sourceCurrencyCode, |
| | | 332 | | int? preferredSupplierId, |
| | | 333 | | CurrencyCode? preferredSupplierCurrencyCode, |
| | | 334 | | string providerDisplayName) |
| | | 335 | | { |
| | 0 | 336 | | if (offer == null) |
| | 0 | 337 | | return null; |
| | | 338 | | |
| | 0 | 339 | | var supplierPrice = ParseDecimalInvariant(offer.Price); |
| | 0 | 340 | | if (supplierPrice == null) |
| | 0 | 341 | | return null; |
| | | 342 | | |
| | 0 | 343 | | var roundedPrice = ArmtekPriceCurrencyConverter.ConvertToRub(supplierPrice.Value, rateToRub); |
| | 0 | 344 | | var deliveryDays = TryGetDeliveryDays(offer.DeliveryDate); |
| | 0 | 345 | | var keyzak = offer.Keyzak ?? string.Empty; |
| | 0 | 346 | | var partnerWarehouseCode = offer.PartnerWarehouseCode ?? string.Empty; |
| | 0 | 347 | | storeNameByKeyzak.TryGetValue(keyzak, out var keyzakName); |
| | 0 | 348 | | var direction = BuildDirectionLabel(keyzak, keyzakName, partnerWarehouseCode, providerDisplayName); |
| | 0 | 349 | | var title = BuildSupplierLabel(keyzak, keyzakName, partnerWarehouseCode, providerDisplayName); |
| | 0 | 350 | | var itemId = !string.IsNullOrWhiteSpace(offer.ArtId) |
| | 0 | 351 | | ? offer.ArtId |
| | 0 | 352 | | : $"{offer.Pin}|{offer.Brand}|{direction}"; |
| | | 353 | | |
| | 0 | 354 | | return new PreOrderItem |
| | 0 | 355 | | { |
| | 0 | 356 | | Caption = string.IsNullOrWhiteSpace(offer.Name) ? offer.Pin : offer.Name, |
| | 0 | 357 | | Rest = string.IsNullOrWhiteSpace(offer.Rvalue) ? "0" : offer.Rvalue, |
| | 0 | 358 | | DeliveryDays = deliveryDays?.ToString() ?? "-", |
| | 0 | 359 | | DeliveryDaysMin = deliveryDays ?? 0, |
| | 0 | 360 | | DeliveryDaysMax = deliveryDays ?? 0, |
| | 0 | 361 | | CurrencyCode = "RUB", |
| | 0 | 362 | | Producer = offer.Brand ?? string.Empty, |
| | 0 | 363 | | Code = offer.Pin ?? string.Empty, |
| | 0 | 364 | | Price = roundedPrice.ToString("0", System.Globalization.CultureInfo.InvariantCulture), |
| | 0 | 365 | | CostPrice = roundedPrice.ToString("0", System.Globalization.CultureInfo.InvariantCulture), |
| | 0 | 366 | | CostPriceFormatted = roundedPrice.ToString("0", System.Globalization.CultureInfo.InvariantCulture), |
| | 0 | 367 | | Direction = string.IsNullOrWhiteSpace(direction) ? providerDisplayName : direction, |
| | 0 | 368 | | ItemHash = itemId.GetHashCode().ToString("X"), |
| | 0 | 369 | | ItemId = itemId, |
| | 0 | 370 | | SiteUrl = "https://ws.armtek.ru/", |
| | 0 | 371 | | Title = title, |
| | 0 | 372 | | Description = BuildDescription(offer, deliveryDays, rateToRub), |
| | 0 | 373 | | PriceDescription = BuildPriceDescription(supplierPrice.Value, sourceCurrencyCode, rateToRub, roundedPrice), |
| | 0 | 374 | | SourcePrice = supplierPrice.Value, |
| | 0 | 375 | | SourceCurrencyCode = sourceCurrencyCode.ToString(), |
| | 0 | 376 | | PreferredSupplierId = preferredSupplierId, |
| | 0 | 377 | | PreferredSupplierCurrencyCode = preferredSupplierCurrencyCode?.ToString(), |
| | 0 | 378 | | ProviderData = new Dictionary<string, string?> |
| | 0 | 379 | | { |
| | 0 | 380 | | ["providerKey"] = providerDisplayName == "Армтек BY" ? "ArmtekBy" : "Armtek", |
| | 0 | 381 | | ["artId"] = offer.ArtId, |
| | 0 | 382 | | ["keyzak"] = offer.Keyzak, |
| | 0 | 383 | | ["warehouseName"] = keyzakName, |
| | 0 | 384 | | ["partnerWarehouseCode"] = offer.PartnerWarehouseCode, |
| | 0 | 385 | | ["deliveryAtUtc"] = offer.DeliveryDate |
| | 0 | 386 | | } |
| | 0 | 387 | | }; |
| | | 388 | | } |
| | | 389 | | |
| | 0 | 390 | | private async Task<decimal> GetRateToRubAsync(CurrencyCode currencyCode) => currencyCode switch |
| | 0 | 391 | | { |
| | 0 | 392 | | CurrencyCode.RUB => 1m, |
| | 0 | 393 | | CurrencyCode.USD => await CurrencyRateFetcher.GetUSDRateAsync(), |
| | 0 | 394 | | CurrencyCode.EUR => await CurrencyRateFetcher.GetEURRateAsync(), |
| | 0 | 395 | | CurrencyCode.BYN => await CurrencyRateFetcher.GetBYNRateAsync(), |
| | 0 | 396 | | _ => 1m |
| | 0 | 397 | | }; |
| | | 398 | | |
| | | 399 | | private static CurrencyCode ResolveCurrency(string? value, CurrencyCode fallback) |
| | | 400 | | { |
| | 0 | 401 | | return Enum.TryParse<CurrencyCode>(value, ignoreCase: true, out var currency) |
| | 0 | 402 | | ? currency |
| | 0 | 403 | | : fallback; |
| | | 404 | | } |
| | | 405 | | |
| | | 406 | | private static int? TryGetDeliveryDays(string? deliveryDateRaw) |
| | | 407 | | { |
| | 0 | 408 | | if (string.IsNullOrWhiteSpace(deliveryDateRaw)) |
| | 0 | 409 | | return null; |
| | | 410 | | |
| | 0 | 411 | | if (!DateTime.TryParseExact( |
| | 0 | 412 | | deliveryDateRaw.Trim(), |
| | 0 | 413 | | "yyyyMMddHHmmss", |
| | 0 | 414 | | System.Globalization.CultureInfo.InvariantCulture, |
| | 0 | 415 | | System.Globalization.DateTimeStyles.None, |
| | 0 | 416 | | out var deliveryDate)) |
| | 0 | 417 | | return null; |
| | | 418 | | |
| | 0 | 419 | | var now = DateTime.Now; |
| | 0 | 420 | | var days = (int)Math.Ceiling((deliveryDate - now).TotalDays); |
| | 0 | 421 | | return Math.Max(0, days); |
| | | 422 | | } |
| | | 423 | | |
| | | 424 | | private static decimal? ParseDecimalInvariant(string? value) |
| | | 425 | | { |
| | 0 | 426 | | if (string.IsNullOrWhiteSpace(value)) |
| | 0 | 427 | | return null; |
| | | 428 | | |
| | 0 | 429 | | var normalized = value.Replace(" ", string.Empty).Replace(",", "."); |
| | 0 | 430 | | return decimal.TryParse( |
| | 0 | 431 | | normalized, |
| | 0 | 432 | | System.Globalization.NumberStyles.Any, |
| | 0 | 433 | | System.Globalization.CultureInfo.InvariantCulture, |
| | 0 | 434 | | out var parsed) |
| | 0 | 435 | | ? parsed |
| | 0 | 436 | | : null; |
| | | 437 | | } |
| | | 438 | | |
| | | 439 | | private static string BuildDescription(ArmtekSearchItem offer, int? deliveryDays, decimal rateToRub) |
| | | 440 | | { |
| | 0 | 441 | | var parts = new List<string>(); |
| | 0 | 442 | | if (!string.IsNullOrWhiteSpace(offer.Pin)) parts.Add($"Артикул: {offer.Pin}"); |
| | 0 | 443 | | if (!string.IsNullOrWhiteSpace(offer.Brand)) parts.Add($"Бренд: {offer.Brand}"); |
| | 0 | 444 | | if (!string.IsNullOrWhiteSpace(offer.Keyzak)) parts.Add($"Склад: {offer.Keyzak}"); |
| | 0 | 445 | | if (!string.IsNullOrWhiteSpace(offer.Rvalue)) parts.Add($"Наличие: {offer.Rvalue}"); |
| | 0 | 446 | | if (!string.IsNullOrWhiteSpace(offer.Price)) parts.Add($"Цена API: {offer.Price} {offer.Currency}; курс: {rateTo |
| | 0 | 447 | | if (deliveryDays.HasValue) parts.Add($"Срок: {deliveryDays.Value} дн."); |
| | 0 | 448 | | if (!string.IsNullOrWhiteSpace(offer.Analog)) parts.Add($"Аналог: {offer.Analog}"); |
| | 0 | 449 | | return string.Join("\n", parts); |
| | | 450 | | } |
| | | 451 | | |
| | | 452 | | private static string BuildPriceDescription(decimal sourcePrice, CurrencyCode currencyCode, |
| | | 453 | | decimal rateToRub, decimal rubPrice) => |
| | 0 | 454 | | currencyCode == CurrencyCode.RUB |
| | 0 | 455 | | ? $"Цена API: {sourcePrice:0.##} RUB" |
| | 0 | 456 | | : $"Цена до перевода: {sourcePrice:0.##} {currencyCode}; курс ЦБ РФ: {rateToRub:0.####}; в таблице: {rubPric |
| | | 457 | | |
| | | 458 | | private static string BuildDirectionLabel(string keyzak, string? keyzakName, string partnerWarehouseCode, string pro |
| | | 459 | | { |
| | 0 | 460 | | if (!string.IsNullOrWhiteSpace(keyzakName)) |
| | 0 | 461 | | return $"{keyzakName} ({keyzak})"; |
| | 0 | 462 | | if (!string.IsNullOrWhiteSpace(keyzak)) |
| | 0 | 463 | | return keyzak; |
| | 0 | 464 | | if (!string.IsNullOrWhiteSpace(partnerWarehouseCode)) |
| | 0 | 465 | | return $"Партнёрский склад ({partnerWarehouseCode})"; |
| | 0 | 466 | | return providerDisplayName; |
| | | 467 | | } |
| | | 468 | | |
| | | 469 | | private static string BuildSupplierLabel(string keyzak, string? keyzakName, string partnerWarehouseCode, string prov |
| | | 470 | | { |
| | 0 | 471 | | if (!string.IsNullOrWhiteSpace(keyzakName)) |
| | 0 | 472 | | return $"{providerDisplayName}: {keyzakName}"; |
| | 0 | 473 | | if (!string.IsNullOrWhiteSpace(keyzak)) |
| | 0 | 474 | | return $"{providerDisplayName}: {keyzak}"; |
| | 0 | 475 | | if (!string.IsNullOrWhiteSpace(partnerWarehouseCode)) |
| | 0 | 476 | | return $"{providerDisplayName} (партнёр): {partnerWarehouseCode}"; |
| | 0 | 477 | | return providerDisplayName; |
| | | 478 | | } |
| | | 479 | | } |