| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.RegularExpressions; |
| | | 3 | | using Microsoft.AspNetCore.Authorization; |
| | | 4 | | using Microsoft.AspNetCore.Mvc; |
| | | 5 | | using Microsoft.Extensions.Caching.Memory; |
| | | 6 | | using Newtonsoft.Json.Linq; |
| | | 7 | | using OzonDomains; |
| | | 8 | | using OzonDomains.Models; |
| | | 9 | | using Services.ApiServices.MotexApi; |
| | | 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 MotexPriceController : Controller |
| | | 23 | | { |
| | | 24 | | private readonly MotexDataManager _motex; |
| | | 25 | | private readonly ApiSupplierSettingsService _settingsService; |
| | | 26 | | private readonly ICurrencyRateFetcher _currencyRateFetcher; |
| | | 27 | | private readonly IMemoryCache _cache; |
| | | 28 | | |
| | 8 | 29 | | public MotexPriceController( |
| | 8 | 30 | | MotexDataManager motex, |
| | 8 | 31 | | ApiSupplierSettingsService settingsService, |
| | 8 | 32 | | ICurrencyRateFetcher currencyRateFetcher, |
| | 8 | 33 | | IMemoryCache cache) |
| | | 34 | | { |
| | 8 | 35 | | _motex = motex; |
| | 8 | 36 | | _settingsService = settingsService; |
| | 8 | 37 | | _currencyRateFetcher = currencyRateFetcher; |
| | 8 | 38 | | _cache = cache; |
| | 8 | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary>Read-only проценка Motex (МоТехС), приведённая к общему формату строки транзакции.</summary> |
| | | 42 | | [HttpGet] |
| | | 43 | | public async Task<IActionResult> Search(string code, string? brand, int? orderId) |
| | | 44 | | { |
| | 8 | 45 | | if (string.IsNullOrWhiteSpace(code)) |
| | 1 | 46 | | return BadRequest(new { error = "Не указан артикул для поиска цен МоТехС." }); |
| | | 47 | | |
| | | 48 | | try |
| | | 49 | | { |
| | 7 | 50 | | var settings = await _settingsService.GetMotexAsync(HttpContext.RequestAborted); |
| | 7 | 51 | | if (!settings.IsQuotationEnabled) |
| | 1 | 52 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 53 | | |
| | 6 | 54 | | var deliveryAddresses = await GetDeliveryAddressesAsync(HttpContext.RequestAborted); |
| | 6 | 55 | | var deliveryAddress = deliveryAddresses.Count == 1 ? deliveryAddresses[0] : null; |
| | 6 | 56 | | var deliveryDestination = settings.DeliveryAddress ?? deliveryAddress?.DisplayName; |
| | | 57 | | |
| | 6 | 58 | | var query = new Dictionary<string, string?> |
| | 6 | 59 | | { |
| | 6 | 60 | | ["code"] = code.Trim(), |
| | 6 | 61 | | ["brand"] = brand?.Trim(), |
| | 6 | 62 | | ["withAnalogs"] = "0", |
| | 6 | 63 | | ["deliveryAddressCode"] = deliveryAddress?.Code |
| | 6 | 64 | | }; |
| | | 65 | | |
| | 6 | 66 | | var response = await _motex.GetAsync("/api/v1/Articles/Search", query, HttpContext.RequestAborted); |
| | 5 | 67 | | var articles = (response["articles"] as JArray ?? new JArray()) |
| | 5 | 68 | | .OfType<JObject>() |
| | 11 | 69 | | .Where(x => (x.Value<int?>("isAnalog") ?? 0) == 0); |
| | | 70 | | |
| | 5 | 71 | | var items = articles |
| | 5 | 72 | | .Select(article => MapToPreOrderItem(article, settings.CurrencyCode, settings.SupplierId, settings.Suppl |
| | 5 | 73 | | .Where(item => item != null) |
| | 5 | 74 | | .Cast<PreOrderItem>() |
| | 5 | 75 | | .ToList(); |
| | | 76 | | |
| | 5 | 77 | | return Ok(await ConvertPricesAsync(items)); |
| | | 78 | | } |
| | 1 | 79 | | catch (MotexApiException ex) when (ex.StatusCode == 404) |
| | | 80 | | { |
| | 1 | 81 | | return Ok(Array.Empty<PreOrderItem>()); |
| | | 82 | | } |
| | 0 | 83 | | catch (MotexApiException ex) |
| | | 84 | | { |
| | 0 | 85 | | return BadRequest(new { error = ex.Message }); |
| | | 86 | | } |
| | 8 | 87 | | } |
| | | 88 | | |
| | | 89 | | private async Task<IReadOnlyList<MotexDeliveryAddress>> GetDeliveryAddressesAsync(CancellationToken cancellationToke |
| | | 90 | | { |
| | | 91 | | try |
| | | 92 | | { |
| | 6 | 93 | | var addresses = await _cache.GetOrCreateAsync("api-supplier:motex:delivery-addresses", async entry => |
| | 6 | 94 | | { |
| | 6 | 95 | | entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); |
| | 6 | 96 | | var response = await _motex.GetAsync("/api/v1/Users/GetUserDeliveryAddresses", null, cancellationToken); |
| | 6 | 97 | | return (response["deliveryAddresses"] as JArray ?? new JArray()) |
| | 6 | 98 | | .OfType<JObject>() |
| | 7 | 99 | | .Select(x => new MotexDeliveryAddress( |
| | 7 | 100 | | x.Value<string>("code")?.Trim() ?? string.Empty, |
| | 7 | 101 | | string.Join(", ", new[] { x.Value<string>("city"), x.Value<string>("address"), x.Value<string>(" |
| | 33 | 102 | | .Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value!.Trim()).Distinct() |
| | 7 | 103 | | .Where(x => !string.IsNullOrWhiteSpace(x.Code)) |
| | 6 | 104 | | .ToList(); |
| | 12 | 105 | | }); |
| | 6 | 106 | | return addresses ?? []; |
| | | 107 | | } |
| | 0 | 108 | | catch (MotexApiException) |
| | | 109 | | { |
| | 0 | 110 | | return []; |
| | | 111 | | } |
| | 6 | 112 | | } |
| | | 113 | | |
| | | 114 | | private static PreOrderItem? MapToPreOrderItem( |
| | | 115 | | JObject article, |
| | | 116 | | CurrencyCode fallbackCurrency, |
| | | 117 | | int? preferredSupplierId, |
| | | 118 | | CurrencyCode? preferredSupplierCurrencyCode, |
| | | 119 | | string? deliveryDestination) |
| | | 120 | | { |
| | 5 | 121 | | var sourcePrice = ReadDecimal(article, "price"); |
| | 5 | 122 | | if (sourcePrice is null) |
| | 0 | 123 | | return null; |
| | | 124 | | |
| | 5 | 125 | | var quantity = ReadDecimal(article, "quantity") ?? 0m; |
| | 5 | 126 | | var multiple = ReadDecimal(article, "multiple"); |
| | 5 | 127 | | var storeCode = article.Value<string>("storeCode") ?? string.Empty; |
| | 5 | 128 | | var storeInfo = article.Value<string>("storeInfo"); |
| | 5 | 129 | | var direction = string.IsNullOrWhiteSpace(storeInfo) ? storeCode : storeInfo; |
| | 5 | 130 | | var deliveryDate = ParseMotexDate(article.Value<string>("deliveryDate")); |
| | 5 | 131 | | var deliveryDays = deliveryDate.HasValue |
| | 5 | 132 | | ? Math.Max(0, (int)Math.Ceiling((deliveryDate.Value - DateTimeOffset.UtcNow).TotalDays)) |
| | 5 | 133 | | : (int?)null; |
| | 5 | 134 | | var returnPeriod = article.Value<int?>("returnPeriod"); |
| | 5 | 135 | | var itemId = $"{article.Value<string>("code")}|{storeCode}|{sourcePrice.Value.ToString(CultureInfo.InvariantCult |
| | | 136 | | |
| | 5 | 137 | | return new PreOrderItem |
| | 5 | 138 | | { |
| | 5 | 139 | | Caption = article.Value<string>("description") ?? article.Value<string>("code") ?? string.Empty, |
| | 5 | 140 | | Rest = quantity.ToString("0.##", CultureInfo.InvariantCulture), |
| | 5 | 141 | | DeliveryDays = deliveryDays?.ToString(CultureInfo.InvariantCulture) ?? "-", |
| | 5 | 142 | | DeliveryDaysMin = deliveryDays ?? 0, |
| | 5 | 143 | | DeliveryDaysMax = deliveryDays ?? 0, |
| | 5 | 144 | | CurrencyCode = "RUB", |
| | 5 | 145 | | Producer = article.Value<string>("brand") ?? string.Empty, |
| | 5 | 146 | | Code = article.Value<string>("code") ?? string.Empty, |
| | 5 | 147 | | Direction = direction, |
| | 5 | 148 | | ItemHash = itemId.GetHashCode(StringComparison.Ordinal).ToString("X", CultureInfo.InvariantCulture), |
| | 5 | 149 | | ItemId = itemId, |
| | 5 | 150 | | MinQuantity = multiple.HasValue ? decimal.ToInt32(Math.Max(1m, multiple.Value)) : 1, |
| | 5 | 151 | | SiteUrl = "https://api.motexc.by/", |
| | 5 | 152 | | Title = "МоТехС", |
| | 5 | 153 | | Description = BuildDescription(article, quantity, multiple, direction, deliveryDays, returnPeriod), |
| | 5 | 154 | | SourcePrice = sourcePrice.Value, |
| | 5 | 155 | | SourceCurrencyCode = fallbackCurrency.ToString(), |
| | 5 | 156 | | PreferredSupplierId = preferredSupplierId, |
| | 5 | 157 | | PreferredSupplierCurrencyCode = preferredSupplierCurrencyCode?.ToString(), |
| | 5 | 158 | | ProviderData = new Dictionary<string, string?> |
| | 5 | 159 | | { |
| | 5 | 160 | | ["providerKey"] = ApiSupplierSettings.MotexProviderKey, |
| | 5 | 161 | | ["storeCode"] = storeCode, |
| | 5 | 162 | | ["storeInfo"] = storeInfo, |
| | 5 | 163 | | ["deliveryDestination"] = deliveryDestination, |
| | 5 | 164 | | ["deliveryAtUtc"] = deliveryDate?.ToString("O", CultureInfo.InvariantCulture) |
| | 5 | 165 | | } |
| | 5 | 166 | | }; |
| | | 167 | | } |
| | | 168 | | |
| | 24 | 169 | | private sealed record MotexDeliveryAddress(string Code, string DisplayName); |
| | | 170 | | |
| | | 171 | | private async Task<List<PreOrderItem>> ConvertPricesAsync(List<PreOrderItem> items) |
| | | 172 | | { |
| | 5 | 173 | | var rateCache = new Dictionary<string, decimal>(); |
| | 20 | 174 | | foreach (var item in items) |
| | | 175 | | { |
| | 5 | 176 | | var currency = Enum.TryParse<CurrencyCode>(item.SourceCurrencyCode, true, out var parsed) ? parsed : Currenc |
| | 5 | 177 | | if (!rateCache.TryGetValue(item.SourceCurrencyCode!, out var rate)) |
| | | 178 | | { |
| | 5 | 179 | | rate = await GetRateToRubAsync(currency); |
| | 5 | 180 | | rateCache[item.SourceCurrencyCode!] = rate; |
| | | 181 | | } |
| | | 182 | | |
| | 5 | 183 | | var rubPrice = Math.Round(item.SourcePrice!.Value * rate, 0, MidpointRounding.AwayFromZero); |
| | 5 | 184 | | item.Price = rubPrice.ToString("0", CultureInfo.InvariantCulture); |
| | 5 | 185 | | item.CostPrice = rubPrice.ToString("0", CultureInfo.InvariantCulture); |
| | 5 | 186 | | item.CostPriceFormatted = rubPrice.ToString("0", CultureInfo.InvariantCulture); |
| | 5 | 187 | | item.PriceDescription = BuildPriceDescription(item.SourcePrice.Value, currency, rate, rubPrice); |
| | 5 | 188 | | } |
| | 5 | 189 | | return items; |
| | 5 | 190 | | } |
| | | 191 | | |
| | 5 | 192 | | private async Task<decimal> GetRateToRubAsync(CurrencyCode currency) => currency switch |
| | 5 | 193 | | { |
| | 0 | 194 | | CurrencyCode.RUB => 1m, |
| | 0 | 195 | | CurrencyCode.USD => await _currencyRateFetcher.GetUSDRateAsync(), |
| | 0 | 196 | | CurrencyCode.EUR => await _currencyRateFetcher.GetEURRateAsync(), |
| | 5 | 197 | | CurrencyCode.BYN => await _currencyRateFetcher.GetBYNRateAsync(), |
| | 0 | 198 | | _ => 1m |
| | 5 | 199 | | }; |
| | | 200 | | |
| | | 201 | | private static decimal? ReadDecimal(JObject source, string field) |
| | | 202 | | { |
| | 15 | 203 | | var token = source[field]; |
| | 15 | 204 | | if (token == null || token.Type is JTokenType.Null or JTokenType.Undefined) |
| | 0 | 205 | | return null; |
| | | 206 | | |
| | 15 | 207 | | if (token.Type is JTokenType.Integer or JTokenType.Float) |
| | 10 | 208 | | return token.Value<decimal>(); |
| | | 209 | | |
| | 5 | 210 | | var raw = token.Value<string>(); |
| | 5 | 211 | | if (string.IsNullOrWhiteSpace(raw)) |
| | 0 | 212 | | return null; |
| | | 213 | | |
| | | 214 | | // Motex иногда возвращает количество с суффиксом ("20>" = "от 20 шт."); берём числовую часть. |
| | 5 | 215 | | var match = Regex.Match(raw, @"[-+]?[0-9]+(?:[.,][0-9]+)?"); |
| | 5 | 216 | | if (!match.Success) |
| | 0 | 217 | | return null; |
| | | 218 | | |
| | 5 | 219 | | return decimal.TryParse( |
| | 5 | 220 | | match.Value.Replace(',', '.'), |
| | 5 | 221 | | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, |
| | 5 | 222 | | CultureInfo.InvariantCulture, |
| | 5 | 223 | | out var value) |
| | 5 | 224 | | ? value |
| | 5 | 225 | | : null; |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | private static DateTimeOffset? ParseMotexDate(string? raw) => |
| | 5 | 229 | | !string.IsNullOrWhiteSpace(raw) && DateTime.TryParseExact(raw, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, D |
| | 5 | 230 | | ? new DateTimeOffset(DateTime.SpecifyKind(value, DateTimeKind.Utc)) |
| | 5 | 231 | | : null; |
| | | 232 | | |
| | | 233 | | private static string BuildDescription(JObject article, decimal quantity, decimal? multiple, string direction, int? |
| | | 234 | | { |
| | 5 | 235 | | var parts = new List<string> |
| | 5 | 236 | | { |
| | 5 | 237 | | $"Артикул: {article.Value<string>("code")}", |
| | 5 | 238 | | $"Бренд: {article.Value<string>("brand")}", |
| | 5 | 239 | | $"Наличие: {quantity:0.##}" |
| | 5 | 240 | | }; |
| | 10 | 241 | | if (!string.IsNullOrWhiteSpace(direction)) parts.Add($"Склад: {direction}"); |
| | 10 | 242 | | if (multiple.HasValue) parts.Add($"Кратность: {multiple:0.##}"); |
| | 9 | 243 | | if (deliveryDays.HasValue) parts.Add($"Срок: {deliveryDays} дн."); |
| | 9 | 244 | | if (returnPeriod.HasValue) parts.Add($"Возврат: {returnPeriod} дн."); |
| | 5 | 245 | | var resolutionTag = article.Value<int?>("resolutionTag"); |
| | 5 | 246 | | var remainingMarkup = article.Value<string>("remainingMarkup"); |
| | 5 | 247 | | if (resolutionTag == 1) parts.Add($"П.713: остаток надбавки {remainingMarkup}"); |
| | 38 | 248 | | return string.Join("\n", parts.Where(x => !string.IsNullOrWhiteSpace(x))); |
| | | 249 | | } |
| | | 250 | | |
| | | 251 | | private static string BuildPriceDescription(decimal sourcePrice, CurrencyCode currency, decimal rateToRub, decimal r |
| | 5 | 252 | | currency == CurrencyCode.RUB |
| | 5 | 253 | | ? $"Цена API: {sourcePrice:0.##} RUB" |
| | 5 | 254 | | : $"Цена до перевода: {sourcePrice:0.##} {currency}; курс ЦБ РФ: {rateToRub:0.####}; в таблице: {rubPrice:0} |
| | | 255 | | } |