| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.RegularExpressions; |
| | | 3 | | using Microsoft.AspNetCore.Authorization; |
| | | 4 | | using Microsoft.AspNetCore.Mvc; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | using Microsoft.Extensions.Caching.Memory; |
| | | 7 | | using Newtonsoft.Json.Linq; |
| | | 8 | | using OzonDomains; |
| | | 9 | | using Services.ApiServices.MlAutoApi; |
| | | 10 | | using Services.ApiServices.TradesoftApi.Models.Response; |
| | | 11 | | using Services.ApiSupplierSettingsServices; |
| | | 12 | | using Services.PriceСlculationServices; |
| | | 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 sealed class MlAutoPriceController : Controller |
| | | 23 | | { |
| | | 24 | | private readonly MlAutoDataManager _mlAuto; |
| | | 25 | | private readonly ApiSupplierSettingsService _settings; |
| | | 26 | | private readonly ICurrencyRateFetcher _rates; |
| | | 27 | | private readonly IMemoryCache _cache; |
| | | 28 | | private readonly MlAutoDeliveryAddressMappingService? _deliveryMappings; |
| | | 29 | | |
| | 7 | 30 | | public MlAutoPriceController(MlAutoDataManager mlAuto, ApiSupplierSettingsService settings, ICurrencyRateFetcher rat |
| | 7 | 31 | | MlAutoDeliveryAddressMappingService? deliveryMappings = null) |
| | | 32 | | { |
| | 7 | 33 | | _mlAuto = mlAuto; |
| | 7 | 34 | | _settings = settings; |
| | 7 | 35 | | _rates = rates; |
| | 7 | 36 | | _cache = cache; |
| | 7 | 37 | | _deliveryMappings = deliveryMappings; |
| | 7 | 38 | | } |
| | | 39 | | |
| | | 40 | | [HttpGet] |
| | | 41 | | public async Task<IActionResult> Search(string code, string? brand, int? orderId = null, string? zasylWarehouseName |
| | | 42 | | { |
| | 7 | 43 | | if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(brand)) |
| | 6 | 44 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 45 | | try |
| | | 46 | | { |
| | 1 | 47 | | var settings = await _settings.GetMlAutoAsync(HttpContext.RequestAborted); |
| | 1 | 48 | | if (!settings.IsQuotationEnabled) return Ok(Array.Empty<PreOrderItem>()); |
| | 1 | 49 | | var warehouse = orderId.HasValue && _deliveryMappings is not null |
| | 1 | 50 | | ? await _deliveryMappings.ResolveWarehouseAsync(orderId.Value, zasylWarehouseName, HttpContext.RequestAb |
| | 1 | 51 | | var deliveryMapping = orderId.HasValue && _deliveryMappings is not null |
| | 1 | 52 | | ? await _deliveryMappings.ResolveAsync(orderId.Value, zasylWarehouseName, HttpContext.RequestAborted) : |
| | 1 | 53 | | var apiDeliveryDestination = deliveryMapping is null |
| | 1 | 54 | | ? null |
| | 1 | 55 | | : await ResolveDeliveryDestinationAsync(deliveryMapping.DeliveryAddressId, HttpContext.RequestAborted); |
| | 1 | 56 | | var deliveryDestination = settings.DeliveryAddress ?? apiDeliveryDestination; |
| | 1 | 57 | | var warehouses = await GetWarehousesAsync(HttpContext.RequestAborted); |
| | 1 | 58 | | var response = await _mlAuto.PostAsync("/Search/", new Dictionary<string, string?> |
| | 1 | 59 | | { |
| | 1 | 60 | | ["ARTICLE"] = code.Trim(), ["BRAND"] = brand.Trim(), ["SEARCH_TYPE"] = "0" |
| | 1 | 61 | | }, HttpContext.RequestAborted); |
| | 1 | 62 | | var rate = await _rates.GetBYNRateAsync(); |
| | 1 | 63 | | var items = (response as JArray ?? new JArray()).OfType<JObject>() |
| | 2 | 64 | | .Where(x => string.Equals(x.Value<string>("ANALOG"), "NO", StringComparison.OrdinalIgnoreCase)) |
| | 1 | 65 | | .Select(x => Map(x, warehouses, settings.SupplierId, settings.Supplier?.CurrencyCode, rate, deliveryMapp |
| | 1 | 66 | | deliveryMapping is null ? null : Url.Action("MlAuto", "ApiSupplierSettings", new { area = "Studio2" |
| | 2 | 67 | | .Where(x => x != null).Cast<PreOrderItem>().ToList(); |
| | 1 | 68 | | var warning = orderId.HasValue && _deliveryMappings is not null && deliveryMapping is null |
| | 1 | 69 | | ? warehouse.IsUnknownZasyl |
| | 1 | 70 | | ? $"Засыл «{warehouse.WarehouseName}» не найден среди складов Studio2. Проценка ML-Auto BY выполнена |
| | 1 | 71 | | : "Адрес доставки ML-Auto BY не связан с эффективным складом заказа. Проценка выполнена без адреса д |
| | 1 | 72 | | : null; |
| | 1 | 73 | | var settingsUrl = orderId.HasValue && _deliveryMappings is not null && deliveryMapping is null |
| | 1 | 74 | | ? GetSettingsUrl(warehouse.WarehouseId) |
| | 1 | 75 | | : null; |
| | 1 | 76 | | return Ok(warning is null ? items : new { items, warning, settingsUrl }); |
| | | 77 | | } |
| | 0 | 78 | | catch (MlAutoApiException ex) { return Ok(new { items = Array.Empty<PreOrderItem>(), error = ex.Message }); } |
| | 0 | 79 | | catch (Exception ex) when (ex is HttpRequestException or TimeoutException or TaskCanceledException) |
| | | 80 | | { |
| | 0 | 81 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = "Сервис ML-Auto BY временно недоступен." }); |
| | | 82 | | } |
| | 7 | 83 | | } |
| | | 84 | | |
| | | 85 | | private async Task<IReadOnlyDictionary<string, string>> GetWarehousesAsync(CancellationToken cancellationToken) |
| | | 86 | | { |
| | 1 | 87 | | return await _cache.GetOrCreateAsync("api-supplier:ml-auto:warehouses", async entry => |
| | 1 | 88 | | { |
| | 1 | 89 | | entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); |
| | 1 | 90 | | try |
| | 1 | 91 | | { |
| | 1 | 92 | | var response = await _mlAuto.PostAsync("/ImportersSearch/", null, cancellationToken); |
| | 1 | 93 | | return (response as JArray ?? new JArray()).OfType<JObject>() |
| | 1 | 94 | | .Select(x => new { Code = x.Value<string>("STORAGE_CODE") ?? x.Value<string>("CODE") ?? x.Value<stri |
| | 1 | 95 | | .Where(x => !string.IsNullOrWhiteSpace(x.Code) && !string.IsNullOrWhiteSpace(x.Name)) |
| | 4 | 96 | | .GroupBy(x => x.Code!, StringComparer.OrdinalIgnoreCase).ToDictionary(x => x.Key, x => x.First().Nam |
| | 1 | 97 | | } |
| | 0 | 98 | | catch (MlAutoApiException) { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } |
| | 2 | 99 | | }) ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); |
| | 1 | 100 | | } |
| | | 101 | | |
| | | 102 | | private string? GetSettingsUrl(int? warehouseId) => |
| | 0 | 103 | | Url.Action("MlAuto", "ApiSupplierSettings", new { area = "Studio2" }) + |
| | 0 | 104 | | (warehouseId.HasValue ? $"#mlauto-mapping-{warehouseId.Value}" : string.Empty); |
| | | 105 | | |
| | | 106 | | private async Task<string?> ResolveDeliveryDestinationAsync(string addressId, CancellationToken cancellationToken) |
| | | 107 | | { |
| | 0 | 108 | | var addresses = await _cache.GetOrCreateAsync("api-supplier:ml-auto:delivery-addresses", async entry => |
| | 0 | 109 | | { |
| | 0 | 110 | | entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); |
| | 0 | 111 | | var response = await _mlAuto.GetDeliveryAddressesAsync(cancellationToken); |
| | 0 | 112 | | return (response is JContainer container ? container.DescendantsAndSelf() : [response]).OfType<JObject>() |
| | 0 | 113 | | .Select(x => new { Id = GetValue(x, "ADDRESS_ID", "ID"), Name = GetValue(x, "ADDRESS_NAME", "NAME", "ADD |
| | 0 | 114 | | .Where(x => !string.IsNullOrWhiteSpace(x.Id) && !string.IsNullOrWhiteSpace(x.Name)) |
| | 0 | 115 | | .GroupBy(x => x.Id!, StringComparer.OrdinalIgnoreCase) |
| | 0 | 116 | | .ToDictionary(x => x.Key, x => x.First().Name!, StringComparer.OrdinalIgnoreCase); |
| | 0 | 117 | | }); |
| | 0 | 118 | | return addresses?.GetValueOrDefault(addressId); |
| | 0 | 119 | | } |
| | | 120 | | |
| | 0 | 121 | | private static string? GetValue(JObject source, params string[] names) => names |
| | 0 | 122 | | .Select(name => source.GetValue(name, StringComparison.OrdinalIgnoreCase)?.ToString()?.Trim()) |
| | 0 | 123 | | .FirstOrDefault(value => !string.IsNullOrWhiteSpace(value)); |
| | | 124 | | |
| | | 125 | | private static PreOrderItem? Map(JObject offer, IReadOnlyDictionary<string, string> warehouses, int? supplierId, Cur |
| | | 126 | | MlAutoDeliveryAddressSelection? deliveryMapping, string? deliveryDestination, string? settingsUrl) |
| | | 127 | | { |
| | 1 | 128 | | if (!decimal.TryParse(offer.Value<string>("PRICE")?.Replace(',', '.'), NumberStyles.Number, CultureInfo.Invarian |
| | 1 | 129 | | var quantity = MlAutoValueParser.ParseQuantity(offer.Value<string>("QUANTITY")) ?? 0m; |
| | 1 | 130 | | var min = int.TryParse(offer.Value<string>("MIN"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var p |
| | 1 | 131 | | var storageCode = offer.Value<string>("STORAGE_CODE") ?? string.Empty; |
| | 1 | 132 | | var chance = CleanText(offer.Value<string>("CHANCE")); |
| | | 133 | | // В официальном ImportersSearch нет поля локации: ID — код склада, DESCR — условия поставки. |
| | | 134 | | // Для текущего белорусского аккаунта предложения на витрине ML-Auto отображаются как «Минск»; |
| | | 135 | | // код склада дописываем через пробел, иначе предложения разных складов неразличимы в колонке «Направление». |
| | 1 | 136 | | var direction = string.IsNullOrWhiteSpace(storageCode) ? "Минск" : $"Минск {storageCode}"; |
| | 1 | 137 | | var deliveryConditions = CleanText(warehouses.GetValueOrDefault(storageCode)); |
| | 1 | 138 | | var delivery = DateTime.TryParseExact(offer.Value<string>("DATE"), "yyyyMMddHHmmss", CultureInfo.InvariantCultur |
| | 1 | 139 | | ? Math.Max(0, (date.Date - DateTime.Today).Days) : 0; |
| | 1 | 140 | | var rub = Math.Round(sourcePrice * rate, 0, MidpointRounding.AwayFromZero); |
| | 1 | 141 | | var itemId = string.Join("|", offer.Value<string>("PIN"), storageCode, sourcePrice.ToString(CultureInfo.Invarian |
| | 1 | 142 | | return new PreOrderItem |
| | 1 | 143 | | { |
| | 1 | 144 | | Caption = offer.Value<string>("NAME") ?? offer.Value<string>("PIN"), Producer = offer.Value<string>("BRAND") |
| | 1 | 145 | | Rest = quantity.ToString("0.##", CultureInfo.InvariantCulture), MinQuantity = min, DeliveryDays = delivery.T |
| | 1 | 146 | | Price = rub.ToString("0", CultureInfo.InvariantCulture), CostPrice = rub.ToString("0", CultureInfo.Invariant |
| | 1 | 147 | | SourcePrice = sourcePrice, SourceCurrencyCode = "BYN", Direction = direction, ItemId = itemId, ItemHash = it |
| | 1 | 148 | | PreferredSupplierId = supplierId, PreferredSupplierCurrencyCode = supplierCurrency?.ToString(), |
| | 1 | 149 | | Description = BuildDescription(offer, quantity, storageCode, deliveryConditions), |
| | 1 | 150 | | ProviderData = new Dictionary<string, string?> |
| | 1 | 151 | | { |
| | 1 | 152 | | ["providerKey"] = "MlAuto", |
| | 1 | 153 | | ["storageCode"] = storageCode, |
| | 1 | 154 | | ["deliveryAtUtc"] = offer.Value<string>("DATE"), |
| | 1 | 155 | | ["deliveryConditions"] = deliveryConditions, |
| | 1 | 156 | | ["supplyChance"] = chance, |
| | 1 | 157 | | ["deliveryMappingLinked"] = deliveryMapping is null ? "false" : "true", |
| | 1 | 158 | | ["deliveryMappingAddressId"] = deliveryMapping?.DeliveryAddressId, |
| | 1 | 159 | | ["deliveryMappingAddress"] = deliveryDestination ?? (deliveryMapping is null ? null : $"Адрес ML-Auto BY |
| | 1 | 160 | | ["deliveryDestination"] = deliveryDestination, |
| | 1 | 161 | | ["deliveryMappingSettingsUrl"] = settingsUrl |
| | 1 | 162 | | }, |
| | 1 | 163 | | PriceDescription = $"Цена до перевода: {sourcePrice:0.##} BYN; курс ЦБ РФ: {rate:0.####}; в таблице: {rub:0} |
| | 1 | 164 | | }; |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | private static string BuildDescription(JObject offer, decimal quantity, string storageCode, string? deliveryConditio |
| | | 168 | | { |
| | 1 | 169 | | return string.Join("\n", new[] |
| | 1 | 170 | | { |
| | 1 | 171 | | $"Артикул: {offer.Value<string>("PIN")}", |
| | 1 | 172 | | $"Бренд: {offer.Value<string>("BRAND")}", |
| | 1 | 173 | | "Локация: Минск", |
| | 1 | 174 | | $"Код склада API: {storageCode}", |
| | 1 | 175 | | $"Наличие: {quantity:0.##}", |
| | 1 | 176 | | $"Вероятность: {offer.Value<string>("CHANCE") ?? "—"}%", |
| | 1 | 177 | | $"Возврат: {offer.Value<string>("RETURN_PERIOD") ?? "—"} дн.", |
| | 1 | 178 | | string.IsNullOrWhiteSpace(deliveryConditions) ? null : $"Условия поставки: {deliveryConditions}" |
| | 9 | 179 | | }.Where(x => !string.IsNullOrWhiteSpace(x))!); |
| | | 180 | | } |
| | | 181 | | |
| | 2 | 182 | | private static string? CleanText(string? value) => string.IsNullOrWhiteSpace(value) |
| | 2 | 183 | | ? null |
| | 2 | 184 | | : Regex.Replace(value, "<.*?>", string.Empty, RegexOptions.Singleline).Trim(); |
| | | 185 | | } |