| | | 1 | | using System.Globalization; |
| | | 2 | | using Microsoft.AspNetCore.Authorization; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.Extensions.Caching.Memory; |
| | | 5 | | using Newtonsoft.Json.Linq; |
| | | 6 | | using OzonDomains; |
| | | 7 | | using OzonDomains.Models; |
| | | 8 | | using Services.ApiServices.ShateMApi; |
| | | 9 | | using Services.ApiServices.TradesoftApi.Models.Response; |
| | | 10 | | using Services.ApiSupplierSettingsServices; |
| | | 11 | | using Services.PriceСlculationServices; |
| | | 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 ShateMPriceController : Controller |
| | | 22 | | { |
| | | 23 | | private readonly ShateMDataManager _shateM; |
| | | 24 | | private readonly ApiSupplierSettingsService _settingsService; |
| | | 25 | | private readonly ICurrencyRateFetcher _currencyRateFetcher; |
| | | 26 | | private readonly IMemoryCache _cache; |
| | | 27 | | |
| | 0 | 28 | | public ShateMPriceController( |
| | 0 | 29 | | ShateMDataManager shateM, |
| | 0 | 30 | | ApiSupplierSettingsService settingsService, |
| | 0 | 31 | | ICurrencyRateFetcher currencyRateFetcher, |
| | 0 | 32 | | IMemoryCache cache) |
| | | 33 | | { |
| | 0 | 34 | | _shateM = shateM; |
| | 0 | 35 | | _settingsService = settingsService; |
| | 0 | 36 | | _currencyRateFetcher = currencyRateFetcher; |
| | 0 | 37 | | _cache = cache; |
| | 0 | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary>Read-only проценка Шате-М, приведённая к общему формату строки транзакции.</summary> |
| | | 41 | | [HttpGet] |
| | | 42 | | public async Task<IActionResult> Search(string code, string? brand, int? orderId = null, bool includeAnalogs = false |
| | | 43 | | { |
| | 0 | 44 | | if (string.IsNullOrWhiteSpace(code)) |
| | 0 | 45 | | return BadRequest(new { error = "Не указан артикул для поиска цен Шате‑М." }); |
| | | 46 | | |
| | | 47 | | try |
| | | 48 | | { |
| | 0 | 49 | | var settings = await _settingsService.GetShateMAsync(HttpContext.RequestAborted); |
| | 0 | 50 | | if (!settings.IsQuotationEnabled) |
| | 0 | 51 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 52 | | |
| | 0 | 53 | | var article = await FindArticleAsync(code.Trim(), brand?.Trim()); |
| | 0 | 54 | | if (article == null) |
| | 0 | 55 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 56 | | |
| | 0 | 57 | | var articleId = article.Value<int?>("id"); |
| | 0 | 58 | | if (articleId is null or <= 0) |
| | 0 | 59 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 60 | | |
| | 0 | 61 | | var prices = await _shateM.SearchAsync( |
| | 0 | 62 | | "/api/v1/prices/search", |
| | 0 | 63 | | new JArray(new JObject |
| | 0 | 64 | | { |
| | 0 | 65 | | ["articleId"] = articleId.Value, |
| | 0 | 66 | | ["includeAnalogs"] = includeAnalogs |
| | 0 | 67 | | }), |
| | 0 | 68 | | HttpContext.RequestAborted); |
| | 0 | 69 | | var locationsByCode = await GetLocationsByCodeAsync(HttpContext.RequestAborted); |
| | 0 | 70 | | var deliveryAddresses = await GetDeliveryAddressesAsync(HttpContext.RequestAborted); |
| | 0 | 71 | | var deliveryDestination = settings.DeliveryAddress ?? (deliveryAddresses.Count == 1 ? deliveryAddresses[0] : |
| | | 72 | | |
| | 0 | 73 | | var items = new List<PreOrderItem>(); |
| | 0 | 74 | | foreach (var offer in GetOffers(prices)) |
| | | 75 | | { |
| | 0 | 76 | | var item = await MapToPreOrderItemAsync(offer, article, settings.CurrencyCode, locationsByCode, |
| | 0 | 77 | | settings.SupplierId, settings.Supplier?.CurrencyCode, deliveryDestination); |
| | 0 | 78 | | if (item != null) |
| | 0 | 79 | | items.Add(item); |
| | | 80 | | } |
| | 0 | 81 | | return Ok(items); |
| | | 82 | | } |
| | 0 | 83 | | catch (ShateMApiException ex) |
| | | 84 | | { |
| | 0 | 85 | | return BadRequest(new { error = ex.Message }); |
| | | 86 | | } |
| | 0 | 87 | | } |
| | | 88 | | |
| | | 89 | | private async Task<JObject?> FindArticleAsync(string code, string? brand) |
| | | 90 | | { |
| | 0 | 91 | | var key = new JObject { ["articleCode"] = code }; |
| | 0 | 92 | | if (!string.IsNullOrWhiteSpace(brand)) |
| | 0 | 93 | | key["tradeMarkName"] = brand; |
| | | 94 | | |
| | 0 | 95 | | var response = await _shateM.SearchAsync( |
| | 0 | 96 | | "/api/v1/articles/search", |
| | 0 | 97 | | new JObject { ["keys"] = new JArray(key) }, |
| | 0 | 98 | | HttpContext.RequestAborted); |
| | | 99 | | |
| | 0 | 100 | | var articles = response is JArray array |
| | | 101 | | ? array.Select(x => x["article"] as JObject ?? x as JObject).OfType<JObject>() |
| | 0 | 102 | | : Enumerable.Empty<JObject>(); |
| | | 103 | | |
| | 0 | 104 | | return articles.FirstOrDefault(x => string.Equals(x.Value<string>("code"), code, StringComparison.OrdinalIgnoreC |
| | 0 | 105 | | ?? articles.FirstOrDefault(); |
| | 0 | 106 | | } |
| | | 107 | | |
| | | 108 | | private static IEnumerable<JObject> GetOffers(JToken response) |
| | | 109 | | { |
| | 0 | 110 | | var rows = response as JArray ?? response["prices"] as JArray; |
| | 0 | 111 | | if (rows == null) |
| | 0 | 112 | | return Enumerable.Empty<JObject>(); |
| | | 113 | | |
| | 0 | 114 | | return rows.SelectMany(row => row["prices"] is JArray nested ? nested : new JArray(row)) |
| | 0 | 115 | | .OfType<JObject>(); |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | private async Task<IReadOnlyDictionary<string, ShateMLocation>> GetLocationsByCodeAsync(CancellationToken cancellati |
| | | 119 | | { |
| | | 120 | | try |
| | | 121 | | { |
| | 0 | 122 | | var locations = await _cache.GetOrCreateAsync("api-supplier:shatem:locations", async entry => |
| | 0 | 123 | | { |
| | 0 | 124 | | entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); |
| | 0 | 125 | | var response = await _shateM.GetAsync("/api/v1/locations", null, cancellationToken); |
| | 0 | 126 | | return (response as JArray ?? new JArray()) |
| | 0 | 127 | | .OfType<JObject>() |
| | | 128 | | .Select(x => new ShateMLocation( |
| | | 129 | | x.Value<string>("code") ?? string.Empty, |
| | | 130 | | x.Value<string>("name") ?? string.Empty, |
| | | 131 | | x.Value<string>("city") ?? string.Empty)) |
| | | 132 | | .Where(x => !string.IsNullOrWhiteSpace(x.Code)) |
| | | 133 | | .GroupBy(x => x.Code, StringComparer.OrdinalIgnoreCase) |
| | | 134 | | .ToDictionary(x => x.Key, x => x.First(), StringComparer.OrdinalIgnoreCase); |
| | 0 | 135 | | }); |
| | 0 | 136 | | return locations ?? new Dictionary<string, ShateMLocation>(StringComparer.OrdinalIgnoreCase); |
| | | 137 | | } |
| | 0 | 138 | | catch (ShateMApiException) |
| | | 139 | | { |
| | 0 | 140 | | return new Dictionary<string, ShateMLocation>(StringComparer.OrdinalIgnoreCase); |
| | | 141 | | } |
| | 0 | 142 | | } |
| | | 143 | | |
| | | 144 | | private async Task<IReadOnlyList<string>> GetDeliveryAddressesAsync(CancellationToken cancellationToken) |
| | | 145 | | { |
| | | 146 | | try |
| | | 147 | | { |
| | 0 | 148 | | var addresses = await _cache.GetOrCreateAsync("api-supplier:shatem:delivery-addresses", async entry => |
| | 0 | 149 | | { |
| | 0 | 150 | | entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); |
| | 0 | 151 | | var response = await _shateM.GetAsync("/api/v1/delivery/addresses", null, cancellationToken); |
| | 0 | 152 | | return (response as JArray ?? new JArray()).OfType<JObject>() |
| | | 153 | | .Select(address => string.Join(", ", new[] { address.Value<string>("city"), address.Value<string>("a |
| | | 154 | | .Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value!.Trim()).Distinct())) |
| | | 155 | | .Where(value => !string.IsNullOrWhiteSpace(value)) |
| | 0 | 156 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 157 | | .ToList(); |
| | 0 | 158 | | }); |
| | 0 | 159 | | return addresses ?? []; |
| | | 160 | | } |
| | 0 | 161 | | catch (ShateMApiException) |
| | | 162 | | { |
| | 0 | 163 | | return []; |
| | | 164 | | } |
| | 0 | 165 | | } |
| | | 166 | | |
| | | 167 | | private async Task<PreOrderItem?> MapToPreOrderItemAsync( |
| | | 168 | | JObject offer, |
| | | 169 | | JObject article, |
| | | 170 | | CurrencyCode fallbackCurrency, |
| | | 171 | | IReadOnlyDictionary<string, ShateMLocation> locationsByCode, |
| | | 172 | | int? preferredSupplierId, |
| | | 173 | | CurrencyCode? preferredSupplierCurrencyCode, |
| | | 174 | | string? deliveryDestination) |
| | | 175 | | { |
| | 0 | 176 | | var sourcePrice = ReadDecimal(offer, "price.value") ?? ReadDecimal(offer, "price") ?? ReadDecimal(offer, "value" |
| | 0 | 177 | | if (sourcePrice is null) |
| | 0 | 178 | | return null; |
| | | 179 | | |
| | 0 | 180 | | var sourceCurrency = ResolveCurrency(offer.SelectToken("price.currencyCode")?.Value<string>() |
| | 0 | 181 | | ?? offer.Value<string>("currencyCode"), fallbackCurrency); |
| | 0 | 182 | | var rateToRub = await GetRateToRubAsync(sourceCurrency); |
| | 0 | 183 | | var rubPrice = Math.Round(sourcePrice.Value * rateToRub, 0, MidpointRounding.AwayFromZero); |
| | 0 | 184 | | var locationCode = offer.Value<string>("locationCode") ?? offer.SelectToken("location.code")?.Value<string>() ?? |
| | 0 | 185 | | var locationCodeReal = offer.Value<string>("locationCodeReal") ?? string.Empty; |
| | 0 | 186 | | locationsByCode.TryGetValue(locationCode, out var location); |
| | 0 | 187 | | if (location == null && !string.IsNullOrWhiteSpace(locationCodeReal)) |
| | 0 | 188 | | locationsByCode.TryGetValue(locationCodeReal, out location); |
| | 0 | 189 | | var delivery = GetDeliveryDays(offer); |
| | 0 | 190 | | var quantity = ReadDecimal(offer, "quantity.available") ?? ReadDecimal(offer, "quantity") ?? 0m; |
| | 0 | 191 | | var minQuantity = ReadDecimal(offer, "quantity.minimum") ?? 0m; |
| | 0 | 192 | | var multiplicity = ReadDecimal(offer, "quantity.multiplicity"); |
| | 0 | 193 | | var itemId = offer.Value<string>("id") ?? offer.Value<string>("hash") |
| | 0 | 194 | | ?? $"{article.Value<int?>("id")}|{locationCode}|{sourcePrice.Value.ToString(CultureInfo.InvariantCulture)}"; |
| | 0 | 195 | | var direction = FormatLocation(location, locationCode); |
| | | 196 | | |
| | 0 | 197 | | return new PreOrderItem |
| | 0 | 198 | | { |
| | 0 | 199 | | Caption = article.Value<string>("name") ?? article.Value<string>("code") ?? string.Empty, |
| | 0 | 200 | | Rest = quantity.ToString("0.##", CultureInfo.InvariantCulture), |
| | 0 | 201 | | DeliveryDays = delivery.Min?.ToString(CultureInfo.InvariantCulture) ?? "-", |
| | 0 | 202 | | DeliveryDaysMin = delivery.Min ?? 0, |
| | 0 | 203 | | DeliveryDaysMax = delivery.Max ?? delivery.Min ?? 0, |
| | 0 | 204 | | CurrencyCode = "RUB", |
| | 0 | 205 | | Producer = article.Value<string>("tradeMarkName") ?? string.Empty, |
| | 0 | 206 | | Code = article.Value<string>("code") ?? string.Empty, |
| | 0 | 207 | | Price = rubPrice.ToString("0", CultureInfo.InvariantCulture), |
| | 0 | 208 | | CostPrice = rubPrice.ToString("0", CultureInfo.InvariantCulture), |
| | 0 | 209 | | CostPriceFormatted = rubPrice.ToString("0", CultureInfo.InvariantCulture), |
| | 0 | 210 | | Direction = direction, |
| | 0 | 211 | | ItemHash = itemId.GetHashCode(StringComparison.Ordinal).ToString("X", CultureInfo.InvariantCulture), |
| | 0 | 212 | | ItemId = itemId, |
| | 0 | 213 | | MinQuantity = decimal.ToInt32(Math.Max(0m, minQuantity)), |
| | 0 | 214 | | SiteUrl = "https://api.shate-m.by/", |
| | 0 | 215 | | Title = "Шате‑М", |
| | 0 | 216 | | Description = BuildDescription(article, offer, quantity, multiplicity, delivery, sourcePrice.Value, sourceCu |
| | 0 | 217 | | PriceDescription = BuildPriceDescription(sourcePrice.Value, sourceCurrency, rateToRub, rubPrice), |
| | 0 | 218 | | SourcePrice = sourcePrice.Value, |
| | 0 | 219 | | SourceCurrencyCode = sourceCurrency.ToString(), |
| | 0 | 220 | | PreferredSupplierId = preferredSupplierId, |
| | 0 | 221 | | PreferredSupplierCurrencyCode = preferredSupplierCurrencyCode?.ToString(), |
| | 0 | 222 | | ProviderData = new Dictionary<string, string?> |
| | 0 | 223 | | { |
| | 0 | 224 | | ["providerKey"] = ApiSupplierSettings.ShateMProviderKey, |
| | 0 | 225 | | ["priceId"] = itemId, |
| | 0 | 226 | | ["locationCode"] = locationCode, |
| | 0 | 227 | | ["locationCodeReal"] = locationCodeReal, |
| | 0 | 228 | | ["deliveryDestination"] = deliveryDestination |
| | 0 | 229 | | } |
| | 0 | 230 | | }; |
| | 0 | 231 | | } |
| | | 232 | | |
| | | 233 | | private static string FormatLocation(ShateMLocation? location, string fallbackCode) |
| | | 234 | | { |
| | 0 | 235 | | if (location == null) |
| | 0 | 236 | | return string.IsNullOrWhiteSpace(fallbackCode) ? "Шате‑М" : fallbackCode; |
| | 0 | 237 | | if (!string.IsNullOrWhiteSpace(location.City) && !string.IsNullOrWhiteSpace(location.Name)) |
| | 0 | 238 | | return $"{location.City} ({location.Name})"; |
| | 0 | 239 | | return location.Name ?? location.City ?? fallbackCode; |
| | | 240 | | } |
| | | 241 | | |
| | 0 | 242 | | private async Task<decimal> GetRateToRubAsync(CurrencyCode currency) => currency switch |
| | 0 | 243 | | { |
| | 0 | 244 | | CurrencyCode.RUB => 1m, |
| | 0 | 245 | | CurrencyCode.USD => await _currencyRateFetcher.GetUSDRateAsync(), |
| | 0 | 246 | | CurrencyCode.EUR => await _currencyRateFetcher.GetEURRateAsync(), |
| | 0 | 247 | | CurrencyCode.BYN => await _currencyRateFetcher.GetBYNRateAsync(), |
| | 0 | 248 | | _ => 1m |
| | 0 | 249 | | }; |
| | | 250 | | |
| | | 251 | | private static CurrencyCode ResolveCurrency(string? rawCurrency, CurrencyCode fallback) => |
| | 0 | 252 | | Enum.TryParse<CurrencyCode>(rawCurrency, true, out var currency) && currency != CurrencyCode.NON |
| | 0 | 253 | | ? currency |
| | 0 | 254 | | : fallback; |
| | | 255 | | |
| | | 256 | | private static decimal? ReadDecimal(JObject source, string path) |
| | | 257 | | { |
| | 0 | 258 | | var token = source.SelectToken(path); |
| | 0 | 259 | | if (token == null || token.Type is JTokenType.Null or JTokenType.Undefined) |
| | 0 | 260 | | return null; |
| | | 261 | | |
| | 0 | 262 | | if (token.Type is JTokenType.Integer or JTokenType.Float) |
| | 0 | 263 | | return token.Value<decimal>(); |
| | | 264 | | |
| | | 265 | | // Наличие приходит строкой и может нести знак «не менее» («>10», «10>») — без его снятия |
| | | 266 | | // остаток разбирался как отсутствующий и попадал в проценку нулём. |
| | 0 | 267 | | var normalized = token.Value<string>()?.Trim().Replace(" ", string.Empty).Trim('>', '<', '~', '=').Replace(',', |
| | 0 | 268 | | return decimal.TryParse( |
| | 0 | 269 | | normalized, |
| | 0 | 270 | | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, |
| | 0 | 271 | | CultureInfo.InvariantCulture, |
| | 0 | 272 | | out var value) |
| | 0 | 273 | | ? value |
| | 0 | 274 | | : null; |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | private static (int? Min, int? Max) GetDeliveryDays(JObject offer) |
| | | 278 | | { |
| | 0 | 279 | | var dates = (offer["deliveryDateTimes"] as JArray ?? new JArray()) |
| | 0 | 280 | | .Select(x => x["deliveryDateTime"]?.Value<string>()) |
| | 0 | 281 | | .Append(offer["shippingDateTime"]?.Value<string>()) |
| | 0 | 282 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 0 | 283 | | .Select(x => DateTimeOffset.TryParse(x, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out va |
| | 0 | 284 | | .OfType<DateTimeOffset>() |
| | 0 | 285 | | .Select(x => Math.Max(0, (int)Math.Ceiling((x - DateTimeOffset.UtcNow).TotalDays))) |
| | 0 | 286 | | .ToList(); |
| | 0 | 287 | | return dates.Count == 0 ? (null, null) : (dates.Min(), dates.Max()); |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | private static string BuildDescription(JObject article, JObject offer, decimal quantity, decimal? multiplicity, |
| | | 291 | | (int? Min, int? Max) delivery, decimal sourcePrice, CurrencyCode currency, decimal rateToRub, string direction) |
| | | 292 | | { |
| | 0 | 293 | | var parts = new List<string> |
| | 0 | 294 | | { |
| | 0 | 295 | | $"Артикул: {article.Value<string>("code")}", |
| | 0 | 296 | | $"Бренд: {article.Value<string>("tradeMarkName")}", |
| | 0 | 297 | | $"Наличие: {quantity:0.##}", |
| | 0 | 298 | | $"Цена API: {sourcePrice:0.##} {currency}; курс: {rateToRub:0.####}" |
| | 0 | 299 | | }; |
| | 0 | 300 | | if (!string.IsNullOrWhiteSpace(direction)) parts.Add($"Склад: {direction}"); |
| | 0 | 301 | | if (multiplicity.HasValue) parts.Add($"Кратность: {multiplicity:0.##}"); |
| | 0 | 302 | | if (delivery.Min.HasValue) parts.Add(delivery.Max > delivery.Min ? $"Срок: {delivery.Min}–{delivery.Max} дн." : |
| | 0 | 303 | | var warning = offer.SelectToken("addInfo.warningText")?.Value<string>() ?? offer.SelectToken("addInfo.comment")? |
| | 0 | 304 | | if (!string.IsNullOrWhiteSpace(warning)) parts.Add(warning); |
| | 0 | 305 | | return string.Join("\n", parts.Where(x => !string.IsNullOrWhiteSpace(x))); |
| | | 306 | | } |
| | | 307 | | |
| | | 308 | | private static string BuildPriceDescription(decimal sourcePrice, CurrencyCode currency, decimal rateToRub, decimal r |
| | 0 | 309 | | currency == CurrencyCode.RUB |
| | 0 | 310 | | ? $"Цена API: {sourcePrice:0.##} RUB" |
| | 0 | 311 | | : $"Цена до перевода: {sourcePrice:0.##} {currency}; курс ЦБ РФ: {rateToRub:0.####}; в таблице: {rubPrice:0} |
| | | 312 | | |
| | 0 | 313 | | private sealed record ShateMLocation(string Code, string? Name, string? City); |
| | | 314 | | } |