| | | 1 | | using Microsoft.Extensions.Caching.Memory; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Services.ApiServices.FidApi; |
| | | 4 | | using Services.ApiServices.FidApi.Models; |
| | | 5 | | |
| | | 6 | | namespace Services.FeedPriceServices; |
| | | 7 | | |
| | | 8 | | public interface IFeedExplanationReader |
| | | 9 | | { |
| | | 10 | | Task<FeedExplanationResult> GetAsync(string articleKey, long? runId, CancellationToken ct = default); |
| | | 11 | | } |
| | | 12 | | |
| | | 13 | | /// <summary>Читает расшифровку цены через feed API (<c>/api/feed/articles/price-explanation</c>).</summary> |
| | | 14 | | public sealed class FidApiFeedExplanationReader : IFeedExplanationReader |
| | | 15 | | { |
| | | 16 | | private readonly FidApiDataManager _fidApi; |
| | | 17 | | |
| | 10 | 18 | | public FidApiFeedExplanationReader(FidApiDataManager fidApi) => _fidApi = fidApi; |
| | | 19 | | |
| | | 20 | | public async Task<FeedExplanationResult> GetAsync(string articleKey, long? runId, CancellationToken ct = default) |
| | | 21 | | { |
| | 5 | 22 | | var response = await _fidApi.GetPriceExplanationAsync(articleKey, runId, ct) |
| | 5 | 23 | | ?? throw new InvalidOperationException("Фид-сервис не вернул расшифровку цены."); |
| | | 24 | | |
| | 4 | 25 | | return new FeedExplanationResult |
| | 4 | 26 | | { |
| | 4 | 27 | | Key = response.Key, |
| | 4 | 28 | | Found = response.Found, |
| | 4 | 29 | | Explanations = response.Explanations.Select(Map).ToArray() |
| | 4 | 30 | | }; |
| | 4 | 31 | | } |
| | | 32 | | |
| | 8 | 33 | | private static FeedExplanation Map(FidPriceExplanation x) => new() |
| | 8 | 34 | | { |
| | 8 | 35 | | Cabinet = x.CabinetKey, |
| | 8 | 36 | | RunId = x.RunId, |
| | 8 | 37 | | AssembledAt = AsUtc(x.AssembledAt), |
| | 8 | 38 | | AssembledBy = x.AssembledBy ?? string.Empty, |
| | 8 | 39 | | HasFullPlan = x.HasFullPlan, |
| | 8 | 40 | | Found = x.Found, |
| | 8 | 41 | | Outcome = x.Outcome, |
| | 8 | 42 | | Decision = x.Decision, |
| | 8 | 43 | | Reason = x.Reason, |
| | 8 | 44 | | FinalPrice = x.FinalPrice, |
| | 8 | 45 | | OldPrice = x.OldPrice, |
| | 8 | 46 | | MinPrice = x.MinPrice, |
| | 8 | 47 | | PriceWarehouse = x.PriceWarehouse, |
| | 8 | 48 | | PriceSupplier = x.PriceSupplier, |
| | 8 | 49 | | PurchasePrice = x.PurchasePrice, |
| | 8 | 50 | | Multiplicity = x.Multiplicity, |
| | 8 | 51 | | ZeroedWarehouses = x.ZeroedWarehouses, |
| | 8 | 52 | | Formula = x.Formula, |
| | 8 | 53 | | Ozon = x.Ozon, |
| | 8 | 54 | | Correction = x.Correction |
| | 8 | 55 | | }; |
| | | 56 | | |
| | | 57 | | private static DateTimeOffset AsUtc(DateTime value) => |
| | 8 | 58 | | new(value.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(value, DateTimeKind.Utc) : value.ToUniversalTi |
| | | 59 | | } |
| | | 60 | | |
| | | 61 | | public interface IFeedExplanationService |
| | | 62 | | { |
| | | 63 | | /// <summary>Расшифровка по первому ключу, у которого план цен что-то нашёл (ключей до двух).</summary> |
| | | 64 | | Task<FeedExplanationResult> GetAsync(IReadOnlyCollection<string> articleKeys, long? runId, CancellationToken ct = de |
| | | 65 | | } |
| | | 66 | | |
| | | 67 | | /// <summary>Расшифровка цены для окна заказа: кеш 90 с, недоступность feed API возвращается как <c>Error</c> и не кешир |
| | | 68 | | public sealed class FeedExplanationService : IFeedExplanationService |
| | | 69 | | { |
| | | 70 | | private const string CacheKeyPrefix = "feed_explanation_v1_"; |
| | | 71 | | private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(90); |
| | | 72 | | |
| | | 73 | | private readonly IFeedExplanationReader _reader; |
| | | 74 | | private readonly IMemoryCache _cache; |
| | | 75 | | private readonly ILogger<FeedExplanationService> _logger; |
| | | 76 | | |
| | | 77 | | public FeedExplanationService(IFeedExplanationReader reader, IMemoryCache cache, ILogger<FeedExplanationService> log |
| | | 78 | | { |
| | | 79 | | _reader = reader; |
| | | 80 | | _cache = cache; |
| | | 81 | | _logger = logger; |
| | | 82 | | } |
| | | 83 | | |
| | | 84 | | public async Task<FeedExplanationResult> GetAsync(IReadOnlyCollection<string> articleKeys, long? runId, Cancellation |
| | | 85 | | { |
| | | 86 | | var keys = articleKeys |
| | | 87 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | | 88 | | .Select(x => x.Trim()) |
| | | 89 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | | 90 | | .Take(2) |
| | | 91 | | .ToArray(); |
| | | 92 | | if (keys.Length == 0) |
| | | 93 | | return new FeedExplanationResult { Error = "Не удалось собрать ключ артикула: у заказа нет артикула или преф |
| | | 94 | | |
| | | 95 | | FeedExplanationResult? last = null; |
| | | 96 | | foreach (var key in keys) |
| | | 97 | | { |
| | | 98 | | last = await GetOneAsync(key, runId, ct); |
| | | 99 | | if (last.Error is not null || last.Found) return last; |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | return last!; |
| | | 103 | | } |
| | | 104 | | |
| | | 105 | | private async Task<FeedExplanationResult> GetOneAsync(string key, long? runId, CancellationToken ct) |
| | | 106 | | { |
| | | 107 | | var cacheKey = $"{CacheKeyPrefix}{key.ToUpperInvariant()}|{runId?.ToString() ?? "last"}"; |
| | | 108 | | if (_cache.TryGetValue<FeedExplanationResult>(cacheKey, out var cached) && cached is not null) |
| | | 109 | | return cached; |
| | | 110 | | |
| | | 111 | | try |
| | | 112 | | { |
| | | 113 | | var result = await _reader.GetAsync(key, runId, ct); |
| | | 114 | | _cache.Set(cacheKey, result, CacheTtl); |
| | | 115 | | return result; |
| | | 116 | | } |
| | | 117 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 118 | | { |
| | | 119 | | throw; |
| | | 120 | | } |
| | | 121 | | catch (Exception ex) |
| | | 122 | | { |
| | | 123 | | _logger.LogWarning(ex, "Фид: не удалось прочитать расшифровку цены артикула {Key}", key); |
| | | 124 | | return new FeedExplanationResult { Key = key, Error = "Фид-сервис недоступен. Повторите позже." }; |
| | | 125 | | } |
| | | 126 | | } |
| | | 127 | | } |