| | | 1 | | using Microsoft.AspNetCore.Authorization; |
| | | 2 | | using Microsoft.AspNetCore.Mvc; |
| | | 3 | | using Microsoft.Extensions.Caching.Memory; |
| | | 4 | | using Newtonsoft.Json.Linq; |
| | | 5 | | using OzonDomains; |
| | | 6 | | using Services.ApiServices.BergApi; |
| | | 7 | | using Services.ApiServices.TradesoftApi.Models.Response; |
| | | 8 | | using Services.ApiSupplierSettingsServices; |
| | | 9 | | using Services.ProducerAliases; |
| | | 10 | | using OzonOrdersWeb.Filters; |
| | | 11 | | |
| | | 12 | | namespace OzonOrdersWeb.Areas.Studio2.Controllers; |
| | | 13 | | |
| | | 14 | | [Area("Studio2")] |
| | | 15 | | [Authorize(Roles = "User,Admin")] |
| | | 16 | | [ServiceFilter(typeof(SupplierQuotationHistoryFilter), Order = 0)] |
| | | 17 | | [ServiceFilter(typeof(SupplierDeliverySurchargeFilter), Order = 1)] |
| | | 18 | | [ServiceFilter(typeof(SupplierWarehouseRestrictionFilter), Order = 2)] |
| | | 19 | | public sealed class BergPriceController : Controller |
| | | 20 | | { |
| | | 21 | | private readonly BergDataManager _berg; |
| | | 22 | | private readonly ApiSupplierSettingsService _settings; |
| | | 23 | | private readonly ProducerBrandAliasService _brandAliases; |
| | | 24 | | private readonly BergDeliveryAddressMappingService _deliveryAddresses; |
| | | 25 | | |
| | | 26 | | private readonly IMemoryCache _cache; |
| | | 27 | | |
| | | 28 | | /// <summary>Проценка повторяется при каждом открытии документа, а цены за минуту не меняются.</summary> |
| | 0 | 29 | | private static readonly TimeSpan QuotationTtl = TimeSpan.FromMinutes(1); |
| | | 30 | | |
| | 0 | 31 | | public BergPriceController(BergDataManager berg, ApiSupplierSettingsService settings, |
| | 0 | 32 | | ProducerBrandAliasService brandAliases, BergDeliveryAddressMappingService deliveryAddresses, IMemoryCache cache) |
| | | 33 | | { |
| | 0 | 34 | | _berg = berg; |
| | 0 | 35 | | _settings = settings; |
| | 0 | 36 | | _brandAliases = brandAliases; |
| | 0 | 37 | | _deliveryAddresses = deliveryAddresses; |
| | 0 | 38 | | _cache = cache; |
| | 0 | 39 | | } |
| | | 40 | | |
| | | 41 | | [HttpGet] |
| | | 42 | | public async Task<IActionResult> Search(string code, string? brand, int? orderId = null, string? zasylWarehouseName |
| | | 43 | | { |
| | 0 | 44 | | if (string.IsNullOrWhiteSpace(code)) |
| | 0 | 45 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 46 | | |
| | | 47 | | try |
| | | 48 | | { |
| | 0 | 49 | | var settings = await _settings.GetBergAsync(HttpContext.RequestAborted); |
| | 0 | 50 | | if (!settings.IsQuotationEnabled) |
| | 0 | 51 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 52 | | |
| | 0 | 53 | | var addresses = await _berg.GetActiveShipmentAddressesAsync(HttpContext.RequestAborted); |
| | 0 | 54 | | var activeAddress = addresses["shipment_address_list"]?.OfType<JObject>() |
| | 0 | 55 | | .FirstOrDefault(x => x.Value<int?>("state") == 1); |
| | 0 | 56 | | var addressId = activeAddress?.Value<long?>("id"); |
| | 0 | 57 | | var deliveryDestination = activeAddress is null ? null : string.Join(", ", new[] |
| | 0 | 58 | | { |
| | 0 | 59 | | activeAddress.Value<string>("city"), activeAddress.Value<string>("address"), activeAddress.Value<string> |
| | 0 | 60 | | }.Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value!.Trim()).Distinct()); |
| | 0 | 61 | | var response = await _cache.GetOrCreateAsync( |
| | 0 | 62 | | $"quotation:berg:{code.Trim()}:{brand?.Trim()}:{addressId}", |
| | 0 | 63 | | entry => |
| | 0 | 64 | | { |
| | 0 | 65 | | entry.AbsoluteExpirationRelativeToNow = QuotationTtl; |
| | 0 | 66 | | return _berg.GetStockAsync(code.Trim(), brand?.Trim(), includeAnalogs: false, addressId, HttpContext |
| | 0 | 67 | | }); |
| | 0 | 68 | | if (response is null) |
| | 0 | 69 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 70 | | |
| | | 71 | | // Berg параметр brand_name фактически игнорирует и отдаёт все карточки артикула, |
| | | 72 | | // поэтому бренд отсекается здесь — с учётом алиасов, иначе «Kayaba» не совпадёт с «KYB». |
| | 0 | 73 | | var aliases = await _brandAliases.GetMapAsync(HttpContext.RequestAborted); |
| | | 74 | | // Адрес отгрузки Berg привязан к складу заказа: без связи предложение показываем, |
| | | 75 | | // но заказать его через API нельзя — фронтенд узнаёт об этом по deliveryMappingLinked. |
| | 0 | 76 | | var deliveryMapping = await _deliveryAddresses.ResolveAsync(orderId, zasylWarehouseName, HttpContext.Request |
| | 0 | 77 | | return Ok(BergPriceMapper.Map(response, settings.SupplierId, settings.Supplier?.CurrencyCode, |
| | 0 | 78 | | deliveryDestination: settings.DeliveryAddress ?? deliveryMapping?.AddressName ?? deliveryDestination, |
| | 0 | 79 | | requestedBrand: brand?.Trim(), brandAliases: aliases, |
| | 0 | 80 | | deliveryMappingLinked: deliveryMapping is not null, |
| | 0 | 81 | | deliverySettingsUrl: Url.Action("Berg", "ApiSupplierSettings", new { area = "Studio2" }))); |
| | | 82 | | } |
| | 0 | 83 | | catch (BergApiException ex) |
| | | 84 | | { |
| | 0 | 85 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = ex.Message }); |
| | | 86 | | } |
| | 0 | 87 | | catch (Exception ex) when (ex is HttpRequestException or TimeoutException or TaskCanceledException) |
| | | 88 | | { |
| | 0 | 89 | | return Ok(new { items = Array.Empty<PreOrderItem>(), error = "Сервис Berg временно недоступен." }); |
| | | 90 | | } |
| | 0 | 91 | | } |
| | | 92 | | } |