| | | 1 | | using System.Text; |
| | | 2 | | using Hangfire; |
| | | 3 | | using Hangfire.Storage; |
| | | 4 | | using Microsoft.AspNetCore.SignalR; |
| | | 5 | | using Microsoft.Extensions.Http; |
| | | 6 | | using OzonDomains; |
| | | 7 | | using OzonDomains.Models; |
| | | 8 | | using OzonRepositories.Data; |
| | | 9 | | using Services.ApiServices.OzonApi; |
| | | 10 | | using Services.DataServices; |
| | | 11 | | using Services.HangfireService; |
| | | 12 | | using Services.SignalRServices; |
| | | 13 | | using SlqStudio.Application.Services.EmailService; |
| | | 14 | | |
| | | 15 | | namespace Services.BitrixStockServices; |
| | | 16 | | |
| | | 17 | | public class BitrixStockArchiveJobService : IBitrixStockArchiveJobService |
| | | 18 | | { |
| | | 19 | | public const string ArchiveLockKey = "BitrixStock:ArchiveOzonProducts"; |
| | | 20 | | private const int BatchSize = 100; |
| | | 21 | | private const int DelayBetweenBatchesMs = 400; |
| | | 22 | | |
| | | 23 | | private readonly IBitrixStockArchiveJobRepository _repository; |
| | | 24 | | private readonly OzonClientServices _ozonClientServices; |
| | | 25 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 26 | | private readonly IEmailService? _emailService; |
| | | 27 | | private readonly IHubContext<JobProgressHub> _jobProgressHub; |
| | | 28 | | |
| | 0 | 29 | | public BitrixStockArchiveJobService( |
| | 0 | 30 | | IBitrixStockArchiveJobRepository repository, |
| | 0 | 31 | | OzonClientServices ozonClientServices, |
| | 0 | 32 | | IHttpClientFactory httpClientFactory, |
| | 0 | 33 | | IEmailService? emailService, |
| | 0 | 34 | | IHubContext<JobProgressHub> jobProgressHub) |
| | | 35 | | { |
| | 0 | 36 | | _repository = repository; |
| | 0 | 37 | | _ozonClientServices = ozonClientServices; |
| | 0 | 38 | | _httpClientFactory = httpClientFactory; |
| | 0 | 39 | | _emailService = emailService; |
| | 0 | 40 | | _jobProgressHub = jobProgressHub; |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | public async Task<BitrixStockArchiveExecution> CreateExecutionAsync( |
| | | 44 | | string jobId, |
| | | 45 | | IReadOnlyList<BitrixStockArchiveItemDto> items, |
| | | 46 | | string? userId, |
| | | 47 | | string? userName, |
| | | 48 | | string triggerType = "Manual", |
| | | 49 | | CancellationToken cancellationToken = default) |
| | | 50 | | { |
| | 0 | 51 | | var entities = items |
| | 0 | 52 | | .Select((dto, index) => new BitrixStockArchiveItem |
| | 0 | 53 | | { |
| | 0 | 54 | | SortOrder = index, |
| | 0 | 55 | | Article = dto.Article?.Trim(), |
| | 0 | 56 | | OfferId = dto.OfferId?.Trim() ?? "", |
| | 0 | 57 | | OzonProductId = dto.OzonProductId, |
| | 0 | 58 | | OzonClient = dto.OzonClient?.Trim() ?? "", |
| | 0 | 59 | | WasArchived = dto.WasArchived, |
| | 0 | 60 | | Status = dto.WasArchived |
| | 0 | 61 | | ? BitrixStockArchiveItemStatus.Skipped |
| | 0 | 62 | | : BitrixStockArchiveItemStatus.Pending |
| | 0 | 63 | | }) |
| | 0 | 64 | | .ToList(); |
| | | 65 | | |
| | 0 | 66 | | return await _repository.CreateExecutionAsync(jobId.Trim(), null, userId, userName, entities, triggerType, |
| | 0 | 67 | | cancellationToken); |
| | 0 | 68 | | } |
| | | 69 | | |
| | | 70 | | [Queue(HangfireQueueNames.Main)] |
| | | 71 | | public async Task ProcessArchiveAsync(long executionId, string jobId, bool sendHubComplete = true, |
| | | 72 | | CancellationToken cancellationToken = default) |
| | | 73 | | { |
| | 0 | 74 | | var hasHub = !string.IsNullOrWhiteSpace(jobId); |
| | 0 | 75 | | IDisposable? distLock = null; |
| | 0 | 76 | | IStorageConnection? lockConnection = null; |
| | | 77 | | |
| | | 78 | | async Task SendLog(string message) |
| | | 79 | | { |
| | 0 | 80 | | if (hasHub) |
| | | 81 | | { |
| | 0 | 82 | | await _jobProgressHub.Clients.Group(jobId).SendAsync("Log", message, cancellationToken); |
| | | 83 | | } |
| | 0 | 84 | | } |
| | | 85 | | |
| | | 86 | | async Task SendProgress(int current, int total, string statusText) |
| | | 87 | | { |
| | 0 | 88 | | if (hasHub) |
| | | 89 | | { |
| | 0 | 90 | | await _jobProgressHub.Clients.Group(jobId) |
| | 0 | 91 | | .SendAsync("Progress", current, total, statusText ?? "", cancellationToken); |
| | | 92 | | } |
| | 0 | 93 | | } |
| | | 94 | | |
| | | 95 | | async Task SendComplete(bool success, string report) |
| | | 96 | | { |
| | 0 | 97 | | if (hasHub) |
| | | 98 | | { |
| | 0 | 99 | | await _jobProgressHub.Clients.Group(jobId) |
| | 0 | 100 | | .SendAsync("Complete", success, report ?? "", cancellationToken); |
| | | 101 | | } |
| | 0 | 102 | | } |
| | | 103 | | |
| | | 104 | | async Task SendError(string message) |
| | | 105 | | { |
| | 0 | 106 | | if (hasHub) |
| | | 107 | | { |
| | 0 | 108 | | await _jobProgressHub.Clients.Group(jobId).SendAsync("Error", message, cancellationToken); |
| | | 109 | | } |
| | 0 | 110 | | } |
| | | 111 | | |
| | | 112 | | try |
| | | 113 | | { |
| | | 114 | | try |
| | | 115 | | { |
| | 0 | 116 | | lockConnection = JobStorage.Current.GetConnection(); |
| | 0 | 117 | | distLock = lockConnection.AcquireDistributedLock(ArchiveLockKey, TimeSpan.FromMilliseconds(1)); |
| | 0 | 118 | | } |
| | | 119 | | catch (DistributedLockTimeoutException) |
| | | 120 | | { |
| | | 121 | | const string msg = "Архивация уже выполняется. Повторный запуск отменён."; |
| | 0 | 122 | | await SendLog(msg); |
| | 0 | 123 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockArchiveExecutionStatus.Failed, msg, |
| | 0 | 124 | | cancellationToken); |
| | 0 | 125 | | await SendComplete(false, msg); |
| | 0 | 126 | | return; |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | var execution = await _repository.GetExecutionByIdAsync(executionId, includeItems: true, cancellationToken); |
| | 0 | 130 | | if (execution == null) |
| | | 131 | | { |
| | 0 | 132 | | await SendError($"Задание {executionId} не найдено"); |
| | 0 | 133 | | return; |
| | | 134 | | } |
| | | 135 | | |
| | 0 | 136 | | var items = execution.Items.OrderBy(i => i.SortOrder).ToList(); |
| | 0 | 137 | | var total = items.Count; |
| | 0 | 138 | | if (total == 0) |
| | | 139 | | { |
| | 0 | 140 | | await SendLog("Нет позиций для архивации"); |
| | 0 | 141 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockArchiveExecutionStatus.Success, null, |
| | 0 | 142 | | cancellationToken); |
| | 0 | 143 | | await SendComplete(true, "Нет позиций для обработки"); |
| | 0 | 144 | | return; |
| | | 145 | | } |
| | | 146 | | |
| | 0 | 147 | | await SendLog($"Старт архивации: {total} позиций"); |
| | 0 | 148 | | var ozonClients = (await _ozonClientServices.GetOzonClients()) |
| | 0 | 149 | | .Where(c => c.ClientType == ClientType.OZON) |
| | 0 | 150 | | .ToList(); |
| | | 151 | | |
| | 0 | 152 | | var successCount = 0; |
| | 0 | 153 | | var failedCount = 0; |
| | 0 | 154 | | var skippedCount = 0; |
| | 0 | 155 | | var processed = 0; |
| | | 156 | | |
| | 0 | 157 | | foreach (var item in items.Where(i => i.WasArchived)) |
| | | 158 | | { |
| | 0 | 159 | | processed++; |
| | 0 | 160 | | skippedCount++; |
| | 0 | 161 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockArchiveItemStatus.Skipped, |
| | 0 | 162 | | "Уже в архиве", cancellationToken); |
| | 0 | 163 | | await SendLog($"⊘ {item.Article ?? item.OfferId} ({item.OzonClient}): уже в архиве"); |
| | 0 | 164 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 165 | | } |
| | | 166 | | |
| | 0 | 167 | | var toArchive = items.Where(i => !i.WasArchived && i.OzonProductId > 0).ToList(); |
| | 0 | 168 | | var invalid = items.Where(i => !i.WasArchived && i.OzonProductId <= 0).ToList(); |
| | 0 | 169 | | foreach (var item in invalid) |
| | | 170 | | { |
| | 0 | 171 | | processed++; |
| | 0 | 172 | | failedCount++; |
| | | 173 | | const string err = "Не указан product_id Ozon"; |
| | 0 | 174 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockArchiveItemStatus.Failed, err, |
| | 0 | 175 | | cancellationToken); |
| | 0 | 176 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 177 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 178 | | } |
| | | 179 | | |
| | 0 | 180 | | var groups = toArchive.GroupBy(i => i.OzonClient, StringComparer.OrdinalIgnoreCase); |
| | 0 | 181 | | foreach (var clientGroup in groups) |
| | | 182 | | { |
| | 0 | 183 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 184 | | |
| | 0 | 185 | | var client = ozonClients.FirstOrDefault(c => |
| | 0 | 186 | | string.Equals(c.Name, clientGroup.Key, StringComparison.OrdinalIgnoreCase)); |
| | | 187 | | |
| | 0 | 188 | | if (client == null || |
| | 0 | 189 | | string.IsNullOrEmpty(client.DecryptClientId) || |
| | 0 | 190 | | string.IsNullOrEmpty(client.DecryptApiKey)) |
| | | 191 | | { |
| | 0 | 192 | | foreach (var item in clientGroup) |
| | | 193 | | { |
| | 0 | 194 | | processed++; |
| | 0 | 195 | | failedCount++; |
| | 0 | 196 | | var err = $"Клиент Ozon «{clientGroup.Key}» не найден или не настроен"; |
| | 0 | 197 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockArchiveItemStatus.Failed, err, |
| | 0 | 198 | | cancellationToken); |
| | 0 | 199 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 200 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 201 | | } |
| | | 202 | | |
| | 0 | 203 | | continue; |
| | | 204 | | } |
| | | 205 | | |
| | 0 | 206 | | var apiManager = BitrixOzonApiFactory.Create(_httpClientFactory, _emailService, client); |
| | | 207 | | |
| | 0 | 208 | | var clientItems = clientGroup.ToList(); |
| | 0 | 209 | | for (var offset = 0; offset < clientItems.Count; offset += BatchSize) |
| | | 210 | | { |
| | 0 | 211 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 212 | | |
| | 0 | 213 | | var batchItems = clientItems.Skip(offset).Take(BatchSize).ToList(); |
| | 0 | 214 | | var productIds = batchItems.Select(i => i.OzonProductId).Distinct().ToArray(); |
| | 0 | 215 | | await SendLog( |
| | 0 | 216 | | $"Клиент {client.Name}: батч {offset / BatchSize + 1}, product_id: {productIds.Length}"); |
| | | 217 | | |
| | | 218 | | try |
| | | 219 | | { |
| | 0 | 220 | | var ok = await apiManager.ArchiveProductsAsync(productIds); |
| | 0 | 221 | | if (ok) |
| | | 222 | | { |
| | 0 | 223 | | foreach (var item in batchItems) |
| | | 224 | | { |
| | 0 | 225 | | processed++; |
| | 0 | 226 | | successCount++; |
| | 0 | 227 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockArchiveItemStatus.Success, |
| | 0 | 228 | | null, cancellationToken); |
| | 0 | 229 | | await SendLog( |
| | 0 | 230 | | $"✓ {item.Article ?? item.OfferId} → архив ({item.OzonProductId}, {client.Name})"); |
| | 0 | 231 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 232 | | } |
| | | 233 | | } |
| | | 234 | | else |
| | | 235 | | { |
| | | 236 | | const string err = "Ozon вернул result=false"; |
| | 0 | 237 | | foreach (var item in batchItems) |
| | | 238 | | { |
| | 0 | 239 | | processed++; |
| | 0 | 240 | | failedCount++; |
| | 0 | 241 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockArchiveItemStatus.Failed, |
| | 0 | 242 | | err, cancellationToken); |
| | 0 | 243 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 244 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 245 | | } |
| | | 246 | | } |
| | 0 | 247 | | } |
| | 0 | 248 | | catch (Exception ex) |
| | | 249 | | { |
| | 0 | 250 | | foreach (var item in batchItems) |
| | | 251 | | { |
| | 0 | 252 | | processed++; |
| | 0 | 253 | | failedCount++; |
| | 0 | 254 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockArchiveItemStatus.Failed, |
| | 0 | 255 | | ex.Message, cancellationToken); |
| | 0 | 256 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {ex.Message}"); |
| | 0 | 257 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 258 | | } |
| | 0 | 259 | | } |
| | | 260 | | |
| | 0 | 261 | | await _repository.UpdateExecutionCountersAsync(executionId, successCount, failedCount, |
| | 0 | 262 | | cancellationToken); |
| | | 263 | | |
| | 0 | 264 | | if (offset + BatchSize < clientItems.Count) |
| | | 265 | | { |
| | 0 | 266 | | await Task.Delay(DelayBetweenBatchesMs, cancellationToken); |
| | | 267 | | } |
| | 0 | 268 | | } |
| | 0 | 269 | | } |
| | | 270 | | |
| | 0 | 271 | | var finalStatus = failedCount == 0 |
| | 0 | 272 | | ? BitrixStockArchiveExecutionStatus.Success |
| | 0 | 273 | | : successCount == 0 && skippedCount == total |
| | 0 | 274 | | ? BitrixStockArchiveExecutionStatus.Success |
| | 0 | 275 | | : successCount == 0 |
| | 0 | 276 | | ? BitrixStockArchiveExecutionStatus.Failed |
| | 0 | 277 | | : BitrixStockArchiveExecutionStatus.PartialSuccess; |
| | | 278 | | |
| | 0 | 279 | | await _repository.UpdateExecutionCountersAsync(executionId, successCount, failedCount, cancellationToken); |
| | 0 | 280 | | await _repository.CompleteExecutionAsync(executionId, finalStatus, null, cancellationToken); |
| | | 281 | | |
| | 0 | 282 | | var report = BuildReportHtml(executionId, total, successCount, failedCount, skippedCount, finalStatus); |
| | 0 | 283 | | await SendLog($"Готово: успешно {successCount}, пропущено {skippedCount}, ошибок {failedCount}"); |
| | 0 | 284 | | if (sendHubComplete) |
| | | 285 | | { |
| | 0 | 286 | | await SendComplete(failedCount == 0, report); |
| | | 287 | | } |
| | 0 | 288 | | } |
| | 0 | 289 | | catch (Exception ex) |
| | | 290 | | { |
| | 0 | 291 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockArchiveExecutionStatus.Failed, ex.Message, |
| | 0 | 292 | | cancellationToken); |
| | 0 | 293 | | if (sendHubComplete) |
| | | 294 | | { |
| | 0 | 295 | | await SendError(ex.Message); |
| | 0 | 296 | | await SendComplete(false, ex.Message); |
| | | 297 | | } |
| | 0 | 298 | | } |
| | | 299 | | finally |
| | | 300 | | { |
| | 0 | 301 | | HangfireDistributedLockHelper.SafeDispose(ref distLock, ref lockConnection); |
| | | 302 | | } |
| | 0 | 303 | | } |
| | | 304 | | |
| | | 305 | | public Task<(List<BitrixStockArchiveExecution> Items, int Total)> GetExecutionsPageAsync(int page, int pageSize, |
| | | 306 | | CancellationToken cancellationToken = default) => |
| | 0 | 307 | | _repository.GetExecutionsPageAsync(page, pageSize, cancellationToken); |
| | | 308 | | |
| | | 309 | | public Task<BitrixStockArchiveExecution?> GetExecutionDetailsAsync(long id, |
| | | 310 | | CancellationToken cancellationToken = default) => |
| | 0 | 311 | | _repository.GetExecutionByIdAsync(id, includeItems: true, cancellationToken); |
| | | 312 | | |
| | | 313 | | private static string BuildReportHtml(long executionId, int total, int success, int failed, int skipped, |
| | | 314 | | string status) |
| | | 315 | | { |
| | 0 | 316 | | var sb = new StringBuilder(); |
| | 0 | 317 | | sb.Append($"<strong>Задание #{executionId}</strong> — {status}<br>"); |
| | 0 | 318 | | sb.Append($"Всего: {total}, успешно: {success}, пропущено: {skipped}, ошибок: {failed}"); |
| | 0 | 319 | | return sb.ToString(); |
| | | 320 | | } |
| | | 321 | | } |