| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.Extensions.Caching.Memory; |
| | | 3 | | using OzonDomains; |
| | | 4 | | using OzonDomains.Models; |
| | | 5 | | using OzonRepositories.Context; |
| | | 6 | | using Services.FileStorageServices; |
| | | 7 | | |
| | | 8 | | namespace Services.LabelServices; |
| | | 9 | | |
| | | 10 | | /// <summary>Строка каталога сохранённых PDF-этикеток для страницы Labels.</summary> |
| | | 11 | | public sealed class LabelCatalogRow |
| | | 12 | | { |
| | | 13 | | public long Id { get; init; } |
| | | 14 | | public string FileName { get; init; } = string.Empty; |
| | | 15 | | public string ShipmentNumber { get; init; } = string.Empty; |
| | | 16 | | public long SizeBytes { get; init; } |
| | | 17 | | public DateTimeOffset ModifiedAtUtc { get; init; } |
| | | 18 | | public DateTimeOffset PrintedAtUtc { get; init; } |
| | | 19 | | public bool UsesFileDate { get; init; } |
| | | 20 | | public string? PrintedBy { get; init; } |
| | | 21 | | public string PrintSource { get; init; } = string.Empty; |
| | | 22 | | public int? OrderId { get; init; } |
| | | 23 | | public IReadOnlyList<int> RelatedOrderIds { get; init; } = []; |
| | | 24 | | public string? Scanit { get; init; } |
| | | 25 | | public string? Client { get; init; } |
| | | 26 | | public string? Marketplace { get; init; } |
| | | 27 | | public bool HasOrder { get; init; } |
| | | 28 | | public int RelatedOrderCount { get; init; } |
| | | 29 | | |
| | | 30 | | /// <summary>Строковое поле для быстрого поиска ID заказа без клиентской конвертации.</summary> |
| | | 31 | | public string OrderIdText => OrderId?.ToString() ?? string.Empty; |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | public sealed record LabelCatalogSnapshot(DateTimeOffset RefreshedAtUtc, IReadOnlyList<LabelCatalogRow> Rows); |
| | | 35 | | |
| | | 36 | | /// <summary>Общий кэш каталога; хранилище инвалидирует его после изменения PDF.</summary> |
| | | 37 | | public interface ILabelCatalogCache |
| | | 38 | | { |
| | | 39 | | bool TryGet(out LabelCatalogSnapshot? snapshot); |
| | | 40 | | void Set(LabelCatalogSnapshot snapshot); |
| | | 41 | | void Invalidate(); |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | public sealed class LabelCatalogCache : ILabelCatalogCache |
| | | 45 | | { |
| | | 46 | | private const string CacheKey = "labels_catalog_v1"; |
| | | 47 | | private static readonly TimeSpan Expiration = TimeSpan.FromMinutes(10); |
| | | 48 | | private readonly IMemoryCache _cache; |
| | | 49 | | |
| | | 50 | | public LabelCatalogCache(IMemoryCache cache) |
| | | 51 | | { |
| | | 52 | | _cache = cache; |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | public bool TryGet(out LabelCatalogSnapshot? snapshot) => |
| | | 56 | | _cache.TryGetValue(CacheKey, out snapshot); |
| | | 57 | | |
| | | 58 | | public void Set(LabelCatalogSnapshot snapshot) => |
| | | 59 | | _cache.Set(CacheKey, snapshot, Expiration); |
| | | 60 | | |
| | | 61 | | public void Invalidate() => _cache.Remove(CacheKey); |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | public interface ILabelCatalogService |
| | | 65 | | { |
| | | 66 | | Task<LabelCatalogSnapshot> GetSnapshotAsync(bool forceRefresh = false, CancellationToken cancellationToken = default |
| | | 67 | | Task<LabelCatalogSnapshot> RefreshAsync(CancellationToken cancellationToken = default); |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | /// <summary> |
| | | 71 | | /// Сводит записи файлового хранилища и минимальные данные заказов в один кэшируемый каталог. |
| | | 72 | | /// PDF не имеет собственной таблицы, поэтому связь вычисляется по тем же вариантам номера, |
| | | 73 | | /// что применяются при повторном открытии этикетки split-отправления. |
| | | 74 | | /// </summary> |
| | | 75 | | public sealed class LabelCatalogService : ILabelCatalogService |
| | | 76 | | { |
| | 0 | 77 | | private static readonly SemaphoreSlim RefreshLock = new(1, 1); |
| | | 78 | | |
| | | 79 | | private readonly ILabelFileStorage _labelFileStorage; |
| | | 80 | | private readonly ApplicationDbContext _context; |
| | | 81 | | private readonly ILabelCatalogCache _cache; |
| | | 82 | | private readonly ILabelPrintLogService _labelPrintLogService; |
| | | 83 | | |
| | 0 | 84 | | public LabelCatalogService( |
| | 0 | 85 | | ILabelFileStorage labelFileStorage, |
| | 0 | 86 | | ApplicationDbContext context, |
| | 0 | 87 | | ILabelCatalogCache cache, |
| | 0 | 88 | | ILabelPrintLogService labelPrintLogService) |
| | | 89 | | { |
| | 0 | 90 | | _labelFileStorage = labelFileStorage; |
| | 0 | 91 | | _context = context; |
| | 0 | 92 | | _cache = cache; |
| | 0 | 93 | | _labelPrintLogService = labelPrintLogService; |
| | 0 | 94 | | } |
| | | 95 | | |
| | | 96 | | public Task<LabelCatalogSnapshot> GetSnapshotAsync(bool forceRefresh = false, CancellationToken cancellationToken = |
| | 0 | 97 | | forceRefresh ? RefreshAsync(cancellationToken) : GetOrCreateAsync(cancellationToken); |
| | | 98 | | |
| | | 99 | | public async Task<LabelCatalogSnapshot> RefreshAsync(CancellationToken cancellationToken = default) |
| | | 100 | | { |
| | 0 | 101 | | _cache.Invalidate(); |
| | 0 | 102 | | return await GetOrCreateAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 103 | | } |
| | | 104 | | |
| | | 105 | | private async Task<LabelCatalogSnapshot> GetOrCreateAsync(CancellationToken cancellationToken) |
| | | 106 | | { |
| | 0 | 107 | | if (_cache.TryGet(out var cached) && cached is not null) |
| | | 108 | | { |
| | 0 | 109 | | return cached; |
| | | 110 | | } |
| | | 111 | | |
| | 0 | 112 | | await RefreshLock.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 113 | | try |
| | | 114 | | { |
| | 0 | 115 | | if (_cache.TryGet(out cached) && cached is not null) |
| | | 116 | | { |
| | 0 | 117 | | return cached; |
| | | 118 | | } |
| | | 119 | | |
| | 0 | 120 | | var files = await _labelFileStorage.ListAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 121 | | var orders = await _context.Orders.AsNoTracking() |
| | 0 | 122 | | .Where(x => x.ShipmentNumber != null && x.ShipmentNumber != string.Empty) |
| | 0 | 123 | | .Select(x => new CatalogOrder( |
| | 0 | 124 | | x.Id, |
| | 0 | 125 | | x.ShipmentNumber!, |
| | 0 | 126 | | x.Scanit, |
| | 0 | 127 | | x.OzonClient == null ? null : x.OzonClient.Name, |
| | 0 | 128 | | x.OzonClient == null ? null : (ClientType?)x.OzonClient.ClientType)) |
| | 0 | 129 | | .ToListAsync(cancellationToken) |
| | 0 | 130 | | .ConfigureAwait(false); |
| | | 131 | | |
| | 0 | 132 | | var latestLogs = await _labelPrintLogService.GetLatestByPdfAsync(cancellationToken).ConfigureAwait(false); |
| | | 133 | | |
| | 0 | 134 | | var snapshot = new LabelCatalogSnapshot(DateTimeOffset.UtcNow, BuildRows(files, orders, latestLogs)); |
| | 0 | 135 | | _cache.Set(snapshot); |
| | 0 | 136 | | return snapshot; |
| | | 137 | | } |
| | | 138 | | finally |
| | | 139 | | { |
| | 0 | 140 | | RefreshLock.Release(); |
| | | 141 | | } |
| | 0 | 142 | | } |
| | | 143 | | |
| | | 144 | | internal static IReadOnlyList<LabelCatalogRow> BuildRows( |
| | | 145 | | IEnumerable<ServerFileInfo> files, |
| | | 146 | | IEnumerable<CatalogOrder> orders, |
| | | 147 | | IEnumerable<LabelPrintLog>? latestLogs = null) |
| | | 148 | | { |
| | 4 | 149 | | var pdfFiles = files |
| | 7 | 150 | | .Where(x => !x.IsDirectory && x.Name.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) |
| | 4 | 151 | | // Хранилище может кратковременно вернуть один файл дважды. По имени файл |
| | 4 | 152 | | // открывается из корня каталога, поэтому в грид должна попадать одна строка. |
| | 5 | 153 | | .GroupBy(x => x.Name, StringComparer.OrdinalIgnoreCase) |
| | 9 | 154 | | .Select(x => x.OrderByDescending(file => file.LastWriteTimeUtc) |
| | 5 | 155 | | .ThenBy(file => file.RelativePath, StringComparer.OrdinalIgnoreCase) |
| | 4 | 156 | | .First()) |
| | 4 | 157 | | .OrderByDescending(x => x.LastWriteTimeUtc) |
| | 4 | 158 | | .ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase) |
| | 4 | 159 | | .ToList(); |
| | 8 | 160 | | var byFileName = pdfFiles.ToDictionary(x => x.Name, StringComparer.OrdinalIgnoreCase); |
| | 7 | 161 | | var ordersById = orders.ToDictionary(x => x.Id); |
| | 4 | 162 | | var logsByFileName = (latestLogs ?? []) |
| | 1 | 163 | | .GroupBy(x => x.FileName, StringComparer.OrdinalIgnoreCase) |
| | 4 | 164 | | .ToDictionary( |
| | 1 | 165 | | x => x.Key, |
| | 3 | 166 | | x => x.OrderByDescending(log => log.OccurredAtUtc).ThenByDescending(log => log.Id).First(), |
| | 4 | 167 | | StringComparer.OrdinalIgnoreCase); |
| | 4 | 168 | | var related = new Dictionary<string, List<CatalogOrder>>(StringComparer.OrdinalIgnoreCase); |
| | | 169 | | |
| | 14 | 170 | | foreach (var order in orders) |
| | | 171 | | { |
| | 14 | 172 | | foreach (var candidate in OzonPostingNumberHelper.GetLabelFileNameCandidates(order.ShipmentNumber) |
| | 3 | 173 | | .Distinct(StringComparer.OrdinalIgnoreCase)) |
| | | 174 | | { |
| | 4 | 175 | | if (!byFileName.ContainsKey(candidate)) |
| | | 176 | | { |
| | | 177 | | continue; |
| | | 178 | | } |
| | | 179 | | |
| | 3 | 180 | | if (!related.TryGetValue(candidate, out var list)) |
| | | 181 | | { |
| | 2 | 182 | | list = []; |
| | 2 | 183 | | related[candidate] = list; |
| | | 184 | | } |
| | | 185 | | |
| | 3 | 186 | | list.Add(order); |
| | | 187 | | } |
| | | 188 | | } |
| | | 189 | | |
| | 4 | 190 | | return pdfFiles.Select((file, index) => |
| | 4 | 191 | | { |
| | 4 | 192 | | related.TryGetValue(file.Name, out var linked); |
| | 4 | 193 | | linked ??= []; |
| | 4 | 194 | | logsByFileName.TryGetValue(file.Name, out var lastLog); |
| | 4 | 195 | | var fileStem = Path.GetFileNameWithoutExtension(file.Name); |
| | 4 | 196 | | var primary = linked |
| | 3 | 197 | | .OrderByDescending(x => string.Equals(x.ShipmentNumber, fileStem, StringComparison.OrdinalIgnoreCase)) |
| | 3 | 198 | | .ThenBy(x => x.Id) |
| | 4 | 199 | | .FirstOrDefault(); |
| | 4 | 200 | | if (primary is null && lastLog?.OrderId is { } loggedOrderId) |
| | 4 | 201 | | { |
| | 0 | 202 | | ordersById.TryGetValue(loggedOrderId, out primary); |
| | 4 | 203 | | } |
| | 7 | 204 | | var relatedOrderIds = linked.Select(x => x.Id) |
| | 4 | 205 | | .Concat(lastLog?.OrderId is { } loggedId ? [loggedId] : []) |
| | 4 | 206 | | .Distinct() |
| | 3 | 207 | | .OrderBy(x => x) |
| | 4 | 208 | | .ToList(); |
| | 7 | 209 | | var scanits = linked.Select(x => x.Scanit) |
| | 3 | 210 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 4 | 211 | | .Distinct(StringComparer.OrdinalIgnoreCase); |
| | 7 | 212 | | var clients = linked.Select(x => x.Client) |
| | 3 | 213 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 4 | 214 | | .Distinct(StringComparer.OrdinalIgnoreCase); |
| | 7 | 215 | | var marketplaces = linked.Select(x => x.ClientType switch |
| | 7 | 216 | | { |
| | 0 | 217 | | ClientType.YANDEX => "Яндекс", |
| | 3 | 218 | | ClientType.OZON => "Ozon", |
| | 0 | 219 | | _ => string.Empty |
| | 7 | 220 | | }) |
| | 3 | 221 | | .Where(x => !string.IsNullOrEmpty(x)) |
| | 4 | 222 | | .Distinct(StringComparer.Ordinal); |
| | 4 | 223 | | |
| | 4 | 224 | | return new LabelCatalogRow |
| | 4 | 225 | | { |
| | 4 | 226 | | Id = index + 1L, |
| | 4 | 227 | | FileName = file.Name, |
| | 4 | 228 | | ShipmentNumber = primary?.ShipmentNumber ?? fileStem, |
| | 4 | 229 | | SizeBytes = file.Length, |
| | 4 | 230 | | ModifiedAtUtc = file.LastWriteTimeUtc, |
| | 4 | 231 | | PrintedAtUtc = lastLog is null |
| | 4 | 232 | | ? file.LastWriteTimeUtc |
| | 4 | 233 | | : new DateTimeOffset(DateTime.SpecifyKind(lastLog.OccurredAtUtc, DateTimeKind.Utc)), |
| | 4 | 234 | | UsesFileDate = lastLog is null, |
| | 4 | 235 | | PrintedBy = lastLog?.ActorName, |
| | 4 | 236 | | PrintSource = lastLog?.Source switch |
| | 4 | 237 | | { |
| | 0 | 238 | | LabelPrintSource.Studio2 => "Studio2", |
| | 1 | 239 | | LabelPrintSource.PartnerApi => "Partner API", |
| | 3 | 240 | | _ => "Дата файла" |
| | 4 | 241 | | }, |
| | 4 | 242 | | OrderId = primary?.Id, |
| | 4 | 243 | | Scanit = string.Join(" · ", scanits), |
| | 4 | 244 | | Client = string.Join(" · ", clients), |
| | 4 | 245 | | Marketplace = string.Join(" · ", marketplaces), |
| | 4 | 246 | | HasOrder = primary is not null, |
| | 4 | 247 | | RelatedOrderCount = relatedOrderIds.Count, |
| | 4 | 248 | | RelatedOrderIds = relatedOrderIds |
| | 4 | 249 | | }; |
| | 4 | 250 | | }).ToList(); |
| | | 251 | | } |
| | | 252 | | |
| | 31 | 253 | | internal sealed record CatalogOrder(int Id, string ShipmentNumber, string? Scanit, string? Client, ClientType? Clien |
| | | 254 | | } |