| | | 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 OzonOrdersWeb.Filters; |
| | | 13 | | |
| | | 14 | | namespace OzonOrdersWeb.Areas.Studio2.Controllers; |
| | | 15 | | |
| | | 16 | | [Area("Studio2")] |
| | | 17 | | [Authorize(Roles = "User,Admin")] |
| | | 18 | | [ServiceFilter(typeof(SupplierQuotationHistoryFilter), Order = 0)] |
| | | 19 | | [ServiceFilter(typeof(SupplierDeliverySurchargeFilter), Order = 1)] |
| | | 20 | | [ServiceFilter(typeof(SupplierWarehouseRestrictionFilter), Order = 2)] |
| | | 21 | | public sealed class MlAutoRuPriceController : Controller |
| | | 22 | | { |
| | | 23 | | private readonly MlAutoRuDataManager _mlAuto; |
| | | 24 | | private readonly ApiSupplierSettingsService _settings; |
| | | 25 | | private readonly IMemoryCache _cache; |
| | | 26 | | private readonly MlAutoRuDeliveryAddressMappingService _deliveryMappings; |
| | | 27 | | |
| | 0 | 28 | | public MlAutoRuPriceController(MlAutoRuDataManager mlAuto, ApiSupplierSettingsService settings, IMemoryCache cache, |
| | 0 | 29 | | MlAutoRuDeliveryAddressMappingService deliveryMappings) |
| | | 30 | | { |
| | 0 | 31 | | _mlAuto = mlAuto; |
| | 0 | 32 | | _settings = settings; |
| | 0 | 33 | | _cache = cache; |
| | 0 | 34 | | _deliveryMappings = deliveryMappings; |
| | 0 | 35 | | } |
| | | 36 | | |
| | | 37 | | [HttpGet] |
| | | 38 | | public async Task<IActionResult> Search(string code, string? brand, int? orderId = null, string? zasylWarehouseName |
| | | 39 | | { |
| | 0 | 40 | | if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(brand)) |
| | 0 | 41 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 42 | | try |
| | | 43 | | { |
| | 0 | 44 | | var settings = await _settings.GetMlAutoRuAsync(HttpContext.RequestAborted); |
| | 0 | 45 | | if (!settings.IsQuotationEnabled) return Ok(Array.Empty<PreOrderItem>()); |
| | 0 | 46 | | var warehouse = orderId.HasValue |
| | 0 | 47 | | ? await _deliveryMappings.ResolveWarehouseAsync(orderId.Value, zasylWarehouseName, HttpContext.RequestAb |
| | 0 | 48 | | var deliveryMapping = orderId.HasValue |
| | 0 | 49 | | ? await _deliveryMappings.ResolveAsync(orderId.Value, zasylWarehouseName, HttpContext.RequestAborted) : |
| | 0 | 50 | | var apiDeliveryDestination = deliveryMapping is null |
| | 0 | 51 | | ? null |
| | 0 | 52 | | : await ResolveDeliveryDestinationAsync(deliveryMapping.DeliveryAddressId, HttpContext.RequestAborted); |
| | 0 | 53 | | var deliveryDestination = settings.DeliveryAddress ?? apiDeliveryDestination; |
| | 0 | 54 | | var warehouses = await GetWarehousesAsync(HttpContext.RequestAborted); |
| | 0 | 55 | | var response = await _mlAuto.SearchAsync(code.Trim(), brand.Trim(), HttpContext.RequestAborted); |
| | 0 | 56 | | var items = (response as JArray ?? new JArray()).OfType<JObject>() |
| | 0 | 57 | | .Where(x => string.Equals(x.Value<string>("ANALOG"), "NO", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 58 | | .Select(x => Map(x, warehouses, settings.SupplierId, settings.Supplier?.CurrencyCode, deliveryMapping, d |
| | 0 | 59 | | deliveryMapping is null ? null : Url.Action("MlAutoRu", "ApiSupplierSettings", new { area = "Studio2 |
| | 0 | 60 | | .Where(x => x is not null).Cast<PreOrderItem>().ToList(); |
| | 0 | 61 | | var warning = orderId.HasValue && deliveryMapping is null |
| | 0 | 62 | | ? warehouse.IsUnknownZasyl |
| | 0 | 63 | | ? $"Засыл «{warehouse.WarehouseName}» не найден среди складов Studio2. Проценка ML-Auto RU выполнена |
| | 0 | 64 | | : "Адрес доставки ML-Auto RU не связан с эффективным складом заказа. Проценка выполнена без адреса д |
| | 0 | 65 | | : null; |
| | 0 | 66 | | var settingsUrl = orderId.HasValue && deliveryMapping is null |
| | 0 | 67 | | ? GetSettingsUrl(warehouse.WarehouseId) : null; |
| | 0 | 68 | | return Ok(warning is null ? items : new { items, warning, settingsUrl }); |
| | | 69 | | } |
| | 0 | 70 | | catch (MlAutoApiException ex) { return Ok(new { items = Array.Empty<PreOrderItem>(), error = ex.Message }); } |
| | 0 | 71 | | catch (Exception ex) when (ex is HttpRequestException or TimeoutException or TaskCanceledException) |
| | | 72 | | { |
| | 0 | 73 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = "Сервис ML-Auto RU временно недоступен." }); |
| | | 74 | | } |
| | 0 | 75 | | } |
| | | 76 | | |
| | | 77 | | private async Task<IReadOnlyDictionary<string, string>> GetWarehousesAsync(CancellationToken ct) => |
| | 0 | 78 | | await _cache.GetOrCreateAsync("api-supplier:ml-auto-ru:warehouses", async entry => |
| | 0 | 79 | | { |
| | 0 | 80 | | entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); |
| | 0 | 81 | | try |
| | 0 | 82 | | { |
| | 0 | 83 | | var response = await _mlAuto.GetStoragesAsync(ct); |
| | 0 | 84 | | return (response as JArray ?? new JArray()).OfType<JObject>() |
| | 0 | 85 | | .Select(x => new { Code = x.Value<string>("STORAGE_CODE") ?? x.Value<string>("CODE") ?? x.Value<stri |
| | 0 | 86 | | .Where(x => !string.IsNullOrWhiteSpace(x.Code) && !string.IsNullOrWhiteSpace(x.Name)) |
| | 0 | 87 | | .GroupBy(x => x.Code!, StringComparer.OrdinalIgnoreCase).ToDictionary(x => x.Key, x => x.First().Nam |
| | 0 | 88 | | } |
| | 0 | 89 | | catch (MlAutoApiException) { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } |
| | 0 | 90 | | }) ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); |
| | | 91 | | |
| | | 92 | | private string? GetSettingsUrl(int? warehouseId) => |
| | 0 | 93 | | Url.Action("MlAutoRu", "ApiSupplierSettings", new { area = "Studio2" }) + |
| | 0 | 94 | | (warehouseId.HasValue ? $"#mlautoru-mapping-{warehouseId.Value}" : string.Empty); |
| | | 95 | | |
| | | 96 | | private async Task<string?> ResolveDeliveryDestinationAsync(string addressId, CancellationToken cancellationToken) |
| | | 97 | | { |
| | 0 | 98 | | var addresses = await _cache.GetOrCreateAsync("api-supplier:ml-auto-ru:delivery-addresses", async entry => |
| | 0 | 99 | | { |
| | 0 | 100 | | entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); |
| | 0 | 101 | | var response = await _mlAuto.GetDeliveryAddressesAsync(cancellationToken); |
| | 0 | 102 | | return (response is JContainer container ? container.DescendantsAndSelf() : [response]).OfType<JObject>() |
| | 0 | 103 | | .Select(x => new { Id = GetValue(x, "ADDRESS_ID", "ID"), Name = GetValue(x, "ADDRESS_NAME", "NAME", "ADD |
| | 0 | 104 | | .Where(x => !string.IsNullOrWhiteSpace(x.Id) && !string.IsNullOrWhiteSpace(x.Name)) |
| | 0 | 105 | | .GroupBy(x => x.Id!, StringComparer.OrdinalIgnoreCase) |
| | 0 | 106 | | .ToDictionary(x => x.Key, x => x.First().Name!, StringComparer.OrdinalIgnoreCase); |
| | 0 | 107 | | }); |
| | 0 | 108 | | return addresses?.GetValueOrDefault(addressId); |
| | 0 | 109 | | } |
| | | 110 | | |
| | 0 | 111 | | private static string? GetValue(JObject source, params string[] names) => names |
| | 0 | 112 | | .Select(name => source.GetValue(name, StringComparison.OrdinalIgnoreCase)?.ToString()?.Trim()) |
| | 0 | 113 | | .FirstOrDefault(value => !string.IsNullOrWhiteSpace(value)); |
| | | 114 | | |
| | | 115 | | private static PreOrderItem? Map(JObject offer, IReadOnlyDictionary<string, string> warehouses, int? supplierId, Cur |
| | | 116 | | MlAutoDeliveryAddressSelection? deliveryMapping, string? deliveryDestination, string? settingsUrl) |
| | | 117 | | { |
| | 0 | 118 | | if (!decimal.TryParse(offer.Value<string>("PRICE")?.Replace(',', '.'), NumberStyles.Number, CultureInfo.Invarian |
| | 0 | 119 | | var quantity = MlAutoValueParser.ParseQuantity(offer.Value<string>("QUANTITY")) ?? 0m; |
| | 0 | 120 | | var min = int.TryParse(offer.Value<string>("MIN"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var p |
| | 0 | 121 | | var storageCode = offer.Value<string>("STORAGE_CODE") ?? string.Empty; |
| | 0 | 122 | | var conditions = CleanText(warehouses.GetValueOrDefault(storageCode)); |
| | 0 | 123 | | var chance = CleanText(offer.Value<string>("CHANCE")); |
| | | 124 | | // Код склада дописываем через пробел: API отдаёт для всех предложений одну локацию, |
| | | 125 | | // без кода склады неразличимы в колонке «Направление». |
| | 0 | 126 | | var direction = string.IsNullOrWhiteSpace(storageCode) ? "Россия" : $"Россия {storageCode}"; |
| | 0 | 127 | | var delivery = DateTime.TryParseExact(offer.Value<string>("DATE"), "yyyyMMddHHmmss", CultureInfo.InvariantCultur |
| | 0 | 128 | | var rub = Math.Round(sourcePrice, 0, MidpointRounding.AwayFromZero); |
| | 0 | 129 | | var itemId = string.Join("|", offer.Value<string>("PIN"), storageCode, sourcePrice.ToString(CultureInfo.Invarian |
| | 0 | 130 | | return new PreOrderItem |
| | 0 | 131 | | { |
| | 0 | 132 | | Caption = offer.Value<string>("NAME") ?? offer.Value<string>("PIN"), Producer = offer.Value<string>("BRAND") |
| | 0 | 133 | | Rest = quantity.ToString("0.##", CultureInfo.InvariantCulture), MinQuantity = min, DeliveryDays = delivery.T |
| | 0 | 134 | | Price = rub.ToString("0", CultureInfo.InvariantCulture), CostPrice = rub.ToString("0", CultureInfo.Invariant |
| | 0 | 135 | | SourcePrice = sourcePrice, SourceCurrencyCode = "RUB", Direction = direction, ItemId = itemId, ItemHash = it |
| | 0 | 136 | | PreferredSupplierId = supplierId, PreferredSupplierCurrencyCode = supplierCurrency?.ToString(), |
| | 0 | 137 | | Description = BuildDescription(offer, quantity, storageCode, conditions), |
| | 0 | 138 | | ProviderData = new Dictionary<string, string?> |
| | 0 | 139 | | { |
| | 0 | 140 | | ["providerKey"] = "MlAutoRu", ["storageCode"] = storageCode, ["deliveryAtUtc"] = offer.Value<string>("DA |
| | 0 | 141 | | ["deliveryMappingLinked"] = deliveryMapping is null ? "false" : "true", ["deliveryMappingAddressId"] = d |
| | 0 | 142 | | ["deliveryMappingAddress"] = deliveryDestination ?? (deliveryMapping is null ? null : $"Адрес ML-Auto RU |
| | 0 | 143 | | }, |
| | 0 | 144 | | PriceDescription = $"Цена ML-Auto RU: {sourcePrice:0.##} RUB; в таблице: {rub:0} RUB" |
| | 0 | 145 | | }; |
| | | 146 | | } |
| | | 147 | | |
| | 0 | 148 | | private static string BuildDescription(JObject offer, decimal quantity, string storageCode, string? conditions) => s |
| | 0 | 149 | | { |
| | 0 | 150 | | $"Артикул: {offer.Value<string>("PIN")}", $"Бренд: {offer.Value<string>("BRAND")}", "Локация: Россия", $"Код скл |
| | 0 | 151 | | $"Вероятность: {offer.Value<string>("CHANCE") ?? "—"}%", $"Возврат: {offer.Value<string>("RETURN_PERIOD") ?? "—" |
| | 0 | 152 | | }.Where(x => !string.IsNullOrWhiteSpace(x))!); |
| | | 153 | | |
| | 0 | 154 | | private static string? CleanText(string? value) => string.IsNullOrWhiteSpace(value) ? null : Regex.Replace(value, "< |
| | | 155 | | } |