| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using OzonDomains.Models; |
| | | 6 | | using OzonRepositories.Context; |
| | | 7 | | using Services.ApiServices.TradesoftApi.Models.Response; |
| | | 8 | | |
| | | 9 | | namespace Services.ApiSupplierSettingsServices; |
| | | 10 | | |
| | | 11 | | public interface ISupplierQuotationHistoryService |
| | | 12 | | { |
| | | 13 | | Task RecordAsync(string providerKey, int? orderId, string article, string? brand, int? supplierId, |
| | | 14 | | IEnumerable<PreOrderItem>? offers, DateTime requestedAtUtc, Stopwatch stopwatch, string? error = null, |
| | | 15 | | string? requestParametersJson = null, |
| | | 16 | | CancellationToken cancellationToken = default); |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | /// <summary>Сохраняет историю проценки, не влияя на пользовательский ответ при сбое журнала.</summary> |
| | | 20 | | public sealed class SupplierQuotationHistoryService : ISupplierQuotationHistoryService |
| | | 21 | | { |
| | 1 | 22 | | private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); |
| | | 23 | | private readonly ApplicationDbContext _context; |
| | | 24 | | private readonly ILogger<SupplierQuotationHistoryService> _logger; |
| | | 25 | | |
| | 6 | 26 | | public SupplierQuotationHistoryService(ApplicationDbContext context, ILogger<SupplierQuotationHistoryService> logger |
| | | 27 | | { |
| | 6 | 28 | | _context = context; |
| | 6 | 29 | | _logger = logger; |
| | 6 | 30 | | } |
| | | 31 | | |
| | | 32 | | public async Task RecordAsync(string providerKey, int? orderId, string article, string? brand, int? supplierId, |
| | | 33 | | IEnumerable<PreOrderItem>? offers, DateTime requestedAtUtc, Stopwatch stopwatch, string? error = null, |
| | | 34 | | string? requestParametersJson = null, |
| | | 35 | | CancellationToken cancellationToken = default) |
| | | 36 | | { |
| | | 37 | | try |
| | | 38 | | { |
| | 6 | 39 | | if (!orderId.HasValue || orderId.Value <= 0) |
| | 0 | 40 | | return; |
| | | 41 | | |
| | 6 | 42 | | var productId = await _context.Orders.AsNoTracking() |
| | 6 | 43 | | .Where(x => x.Id == orderId.Value) |
| | 6 | 44 | | .Select(x => x.ProductInfoId) |
| | 6 | 45 | | .SingleOrDefaultAsync(cancellationToken); |
| | 5 | 46 | | if (!productId.HasValue) |
| | | 47 | | { |
| | 1 | 48 | | _logger.LogWarning("Проценка {ProviderKey} заказа {OrderId} не сохранена: у заказа нет ProductInfoId.", |
| | 1 | 49 | | return; |
| | | 50 | | } |
| | | 51 | | |
| | 4 | 52 | | if (!supplierId.HasValue) |
| | | 53 | | { |
| | 3 | 54 | | supplierId = await _context.ApiSupplierSettings.AsNoTracking() |
| | 3 | 55 | | .Where(x => x.ProviderKey == providerKey) |
| | 3 | 56 | | .Select(x => x.SupplierId) |
| | 3 | 57 | | .SingleOrDefaultAsync(cancellationToken); |
| | | 58 | | } |
| | | 59 | | |
| | 4 | 60 | | var items = offers?.ToList() ?? []; |
| | 3 | 61 | | var completedAtUtc = DateTime.UtcNow; |
| | 3 | 62 | | var request = new SupplierQuotationRequest |
| | 3 | 63 | | { |
| | 3 | 64 | | ProductId = productId.Value, |
| | 3 | 65 | | OrderId = orderId.Value, |
| | 3 | 66 | | ProviderKey = providerKey, |
| | 3 | 67 | | SupplierId = supplierId, |
| | 3 | 68 | | Article = article.Trim(), |
| | 3 | 69 | | Brand = string.IsNullOrWhiteSpace(brand) ? null : brand.Trim(), |
| | 3 | 70 | | Status = error is not null ? "Failed" : items.Count == 0 ? "Empty" : "Success", |
| | 3 | 71 | | RequestedAtUtc = requestedAtUtc, |
| | 3 | 72 | | CompletedAtUtc = completedAtUtc, |
| | 3 | 73 | | DurationMs = stopwatch.ElapsedMilliseconds, |
| | 3 | 74 | | OffersCount = items.Count, |
| | 3 | 75 | | ErrorMessage = Truncate(error, 2000), |
| | 3 | 76 | | RequestParametersJson = requestParametersJson ?? JsonSerializer.Serialize(new { article = article.Trim() |
| | 3 | 77 | | Offers = items.Select(Map).ToList() |
| | 3 | 78 | | }; |
| | 3 | 79 | | await _context.SupplierQuotationRequests.AddAsync(request, cancellationToken); |
| | 3 | 80 | | await _context.SaveChangesAsync(cancellationToken); |
| | 3 | 81 | | } |
| | | 82 | | // Пользователь ушёл со страницы или отменил проценку — HttpContext.RequestAborted гасит |
| | | 83 | | // запрос к БД на полпути, и история не пишется. Это штатный исход, а не сбой журнала: |
| | | 84 | | // уровень Warning и выше попадает в errors-*.log и заводит автоматический issue. |
| | 2 | 85 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 86 | | { |
| | 1 | 87 | | _logger.LogInformation( |
| | 1 | 88 | | "История проценки {ProviderKey} для заказа {OrderId} не сохранена: запрос отменён клиентом.", |
| | 1 | 89 | | providerKey, orderId); |
| | 1 | 90 | | } |
| | 1 | 91 | | catch (Exception ex) |
| | | 92 | | { |
| | 1 | 93 | | _logger.LogError(ex, "Не удалось сохранить историю проценки {ProviderKey} для заказа {OrderId}.", providerKe |
| | 1 | 94 | | } |
| | 6 | 95 | | } |
| | | 96 | | |
| | 1 | 97 | | private static SupplierQuotationOffer Map(PreOrderItem item) => new() |
| | 1 | 98 | | { |
| | 1 | 99 | | Caption = Truncate(item.Caption, 255), Direction = Truncate(item.Direction, 255), Producer = Truncate(item.Produ |
| | 1 | 100 | | Rest = Truncate(item.Rest, 80), MinQuantity = item.MinQuantity, DeliveryDaysMin = item.DeliveryDaysMin, Delivery |
| | 1 | 101 | | DeliveryDays = Truncate(item.DeliveryDays, 80), ExtraDeliveryHours = item.ExtraDeliveryHours, CurrencyCode = Tru |
| | 1 | 102 | | CostPrice = Truncate(item.CostPrice, 80), CostPriceFormatted = Truncate(item.CostPriceFormatted, 80), SourcePric |
| | 1 | 103 | | SourceCurrencyCode = Truncate(item.SourceCurrencyCode, 32), ItemId = Truncate(item.ItemId, 255), ItemHash = Trun |
| | 1 | 104 | | SiteUrl = Truncate(item.SiteUrl, 1000), Title = Truncate(item.Title, 255), Description = item.Description, Price |
| | 1 | 105 | | ProviderDataJson = item.ProviderData is null ? null : JsonSerializer.Serialize(item.ProviderData, JsonOptions) |
| | 1 | 106 | | }; |
| | | 107 | | |
| | 18 | 108 | | private static string? Truncate(string? value, int length) => string.IsNullOrEmpty(value) || value.Length <= length |
| | | 109 | | } |