| | | 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 BitrixStockUnarchiveJobService : IBitrixStockUnarchiveJobService |
| | | 18 | | { |
| | | 19 | | public const string UnarchiveLockKey = "BitrixStock:UnarchiveOzonProducts"; |
| | | 20 | | private const int BatchSize = 100; |
| | | 21 | | private const int DelayBetweenBatchesMs = 400; |
| | | 22 | | |
| | | 23 | | private readonly IBitrixStockUnarchiveJobRepository _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 BitrixStockUnarchiveJobService( |
| | 0 | 30 | | IBitrixStockUnarchiveJobRepository 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<BitrixStockUnarchiveExecution> CreateExecutionAsync( |
| | | 44 | | string jobId, |
| | | 45 | | IReadOnlyList<BitrixStockUnarchiveItemDto> 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 BitrixStockUnarchiveItem |
| | 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 | | IsAutoArchived = dto.IsAutoArchived, |
| | 0 | 60 | | IsManualArchived = dto.IsManualArchived, |
| | 0 | 61 | | WasInArchive = dto.WasInArchive, |
| | 0 | 62 | | Status = dto.WasInArchive |
| | 0 | 63 | | ? BitrixStockUnarchiveItemStatus.Pending |
| | 0 | 64 | | : BitrixStockUnarchiveItemStatus.Skipped |
| | 0 | 65 | | }) |
| | 0 | 66 | | .ToList(); |
| | | 67 | | |
| | 0 | 68 | | return await _repository.CreateExecutionAsync(jobId.Trim(), null, userId, userName, entities, triggerType, |
| | 0 | 69 | | cancellationToken); |
| | 0 | 70 | | } |
| | | 71 | | |
| | | 72 | | [Queue(HangfireQueueNames.Main)] |
| | | 73 | | public async Task ProcessUnarchiveAsync(long executionId, string jobId, bool sendHubComplete = true, |
| | | 74 | | CancellationToken cancellationToken = default) |
| | | 75 | | { |
| | 0 | 76 | | var hasHub = !string.IsNullOrWhiteSpace(jobId); |
| | 0 | 77 | | IDisposable? distLock = null; |
| | 0 | 78 | | IStorageConnection? lockConnection = null; |
| | | 79 | | |
| | | 80 | | async Task SendLog(string message) |
| | | 81 | | { |
| | 0 | 82 | | if (hasHub) |
| | | 83 | | { |
| | 0 | 84 | | await _jobProgressHub.Clients.Group(jobId).SendAsync("Log", message, cancellationToken); |
| | | 85 | | } |
| | 0 | 86 | | } |
| | | 87 | | |
| | | 88 | | async Task SendProgress(int current, int total, string statusText) |
| | | 89 | | { |
| | 0 | 90 | | if (hasHub) |
| | | 91 | | { |
| | 0 | 92 | | await _jobProgressHub.Clients.Group(jobId) |
| | 0 | 93 | | .SendAsync("Progress", current, total, statusText ?? "", cancellationToken); |
| | | 94 | | } |
| | 0 | 95 | | } |
| | | 96 | | |
| | | 97 | | async Task SendComplete(bool success, string report) |
| | | 98 | | { |
| | 0 | 99 | | if (hasHub) |
| | | 100 | | { |
| | 0 | 101 | | await _jobProgressHub.Clients.Group(jobId) |
| | 0 | 102 | | .SendAsync("Complete", success, report ?? "", cancellationToken); |
| | | 103 | | } |
| | 0 | 104 | | } |
| | | 105 | | |
| | | 106 | | async Task SendError(string message) |
| | | 107 | | { |
| | 0 | 108 | | if (hasHub) |
| | | 109 | | { |
| | 0 | 110 | | await _jobProgressHub.Clients.Group(jobId).SendAsync("Error", message, cancellationToken); |
| | | 111 | | } |
| | 0 | 112 | | } |
| | | 113 | | |
| | | 114 | | try |
| | | 115 | | { |
| | | 116 | | try |
| | | 117 | | { |
| | 0 | 118 | | lockConnection = JobStorage.Current.GetConnection(); |
| | 0 | 119 | | distLock = lockConnection.AcquireDistributedLock(UnarchiveLockKey, TimeSpan.FromMilliseconds(1)); |
| | 0 | 120 | | } |
| | | 121 | | catch (DistributedLockTimeoutException) |
| | | 122 | | { |
| | | 123 | | const string msg = "Разархивация уже выполняется. Повторный запуск отменён."; |
| | 0 | 124 | | await SendLog(msg); |
| | 0 | 125 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockUnarchiveExecutionStatus.Failed, msg, |
| | 0 | 126 | | cancellationToken); |
| | 0 | 127 | | await SendComplete(false, msg); |
| | 0 | 128 | | return; |
| | | 129 | | } |
| | | 130 | | |
| | 0 | 131 | | var execution = await _repository.GetExecutionByIdAsync(executionId, includeItems: true, cancellationToken); |
| | 0 | 132 | | if (execution == null) |
| | | 133 | | { |
| | 0 | 134 | | await SendError($"Задание {executionId} не найдено"); |
| | 0 | 135 | | return; |
| | | 136 | | } |
| | | 137 | | |
| | 0 | 138 | | var items = execution.Items.OrderBy(i => i.SortOrder).ToList(); |
| | 0 | 139 | | var total = items.Count; |
| | 0 | 140 | | if (total == 0) |
| | | 141 | | { |
| | 0 | 142 | | await SendLog("Нет позиций для разархивации"); |
| | 0 | 143 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockUnarchiveExecutionStatus.Success, null, |
| | 0 | 144 | | cancellationToken); |
| | 0 | 145 | | await SendComplete(true, "Нет позиций для обработки"); |
| | 0 | 146 | | return; |
| | | 147 | | } |
| | | 148 | | |
| | 0 | 149 | | await SendLog($"Старт разархивации: {total} позиций"); |
| | 0 | 150 | | var ozonClients = (await _ozonClientServices.GetOzonClients()) |
| | 0 | 151 | | .Where(c => c.ClientType == ClientType.OZON) |
| | 0 | 152 | | .ToList(); |
| | | 153 | | |
| | 0 | 154 | | var successCount = 0; |
| | 0 | 155 | | var failedCount = 0; |
| | 0 | 156 | | var skippedCount = 0; |
| | 0 | 157 | | var processed = 0; |
| | | 158 | | |
| | 0 | 159 | | foreach (var item in items.Where(i => !i.WasInArchive)) |
| | | 160 | | { |
| | 0 | 161 | | processed++; |
| | 0 | 162 | | skippedCount++; |
| | 0 | 163 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockUnarchiveItemStatus.Skipped, |
| | 0 | 164 | | "Не в архиве", cancellationToken); |
| | 0 | 165 | | await SendLog($"⊘ {item.Article ?? item.OfferId} ({item.OzonClient}): не в архиве"); |
| | 0 | 166 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 167 | | } |
| | | 168 | | |
| | 0 | 169 | | var toUnarchive = items.Where(i => i.WasInArchive && i.OzonProductId > 0).ToList(); |
| | 0 | 170 | | var invalid = items.Where(i => i.WasInArchive && i.OzonProductId <= 0).ToList(); |
| | 0 | 171 | | foreach (var item in invalid) |
| | | 172 | | { |
| | 0 | 173 | | processed++; |
| | 0 | 174 | | failedCount++; |
| | | 175 | | const string err = "Не указан product_id Ozon"; |
| | 0 | 176 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockUnarchiveItemStatus.Failed, err, |
| | 0 | 177 | | cancellationToken); |
| | 0 | 178 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 179 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 180 | | } |
| | | 181 | | |
| | 0 | 182 | | var groups = toUnarchive.GroupBy(i => i.OzonClient, StringComparer.OrdinalIgnoreCase); |
| | 0 | 183 | | foreach (var clientGroup in groups) |
| | | 184 | | { |
| | 0 | 185 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 186 | | |
| | 0 | 187 | | var client = ozonClients.FirstOrDefault(c => |
| | 0 | 188 | | string.Equals(c.Name, clientGroup.Key, StringComparison.OrdinalIgnoreCase)); |
| | | 189 | | |
| | 0 | 190 | | if (client == null || |
| | 0 | 191 | | string.IsNullOrEmpty(client.DecryptClientId) || |
| | 0 | 192 | | string.IsNullOrEmpty(client.DecryptApiKey)) |
| | | 193 | | { |
| | 0 | 194 | | foreach (var item in clientGroup) |
| | | 195 | | { |
| | 0 | 196 | | processed++; |
| | 0 | 197 | | failedCount++; |
| | 0 | 198 | | var err = $"Клиент Ozon «{clientGroup.Key}» не найден или не настроен"; |
| | 0 | 199 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockUnarchiveItemStatus.Failed, err, |
| | 0 | 200 | | cancellationToken); |
| | 0 | 201 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 202 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 203 | | } |
| | | 204 | | |
| | 0 | 205 | | continue; |
| | | 206 | | } |
| | | 207 | | |
| | 0 | 208 | | var apiManager = BitrixOzonApiFactory.Create(_httpClientFactory, _emailService, client); |
| | | 209 | | |
| | 0 | 210 | | var clientItems = clientGroup.ToList(); |
| | 0 | 211 | | for (var offset = 0; offset < clientItems.Count; offset += BatchSize) |
| | | 212 | | { |
| | 0 | 213 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 214 | | |
| | 0 | 215 | | var batchItems = clientItems.Skip(offset).Take(BatchSize).ToList(); |
| | 0 | 216 | | var productIds = batchItems.Select(i => i.OzonProductId).Distinct().ToArray(); |
| | 0 | 217 | | var autoCount = batchItems.Count(i => i.IsAutoArchived); |
| | 0 | 218 | | await SendLog( |
| | 0 | 219 | | $"Клиент {client.Name}: батч {offset / BatchSize + 1}, product_id: {productIds.Length}" + |
| | 0 | 220 | | (autoCount > 0 ? $", авто-архив: {autoCount} (лимит 100/сутки)" : "")); |
| | | 221 | | |
| | | 222 | | try |
| | | 223 | | { |
| | 0 | 224 | | var ok = await apiManager.UnarchiveProductsAsync(productIds); |
| | 0 | 225 | | if (ok) |
| | | 226 | | { |
| | 0 | 227 | | foreach (var item in batchItems) |
| | | 228 | | { |
| | 0 | 229 | | processed++; |
| | 0 | 230 | | successCount++; |
| | 0 | 231 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockUnarchiveItemStatus.Success, |
| | 0 | 232 | | null, cancellationToken); |
| | 0 | 233 | | var typeLabel = item.IsAutoArchived ? "авто" : item.IsManualArchived ? "вручную" : ""; |
| | 0 | 234 | | await SendLog( |
| | 0 | 235 | | $"✓ {item.Article ?? item.OfferId} ← из архива ({item.OzonProductId}, {client.Name}{ |
| | 0 | 236 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 237 | | } |
| | | 238 | | } |
| | | 239 | | else |
| | | 240 | | { |
| | | 241 | | const string err = "Ozon вернул result=false"; |
| | 0 | 242 | | foreach (var item in batchItems) |
| | | 243 | | { |
| | 0 | 244 | | processed++; |
| | 0 | 245 | | failedCount++; |
| | 0 | 246 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockUnarchiveItemStatus.Failed, |
| | 0 | 247 | | err, cancellationToken); |
| | 0 | 248 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 249 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 250 | | } |
| | | 251 | | } |
| | 0 | 252 | | } |
| | 0 | 253 | | catch (Exception ex) |
| | | 254 | | { |
| | 0 | 255 | | var err = FormatUnarchiveError(ex); |
| | 0 | 256 | | foreach (var item in batchItems) |
| | | 257 | | { |
| | 0 | 258 | | processed++; |
| | 0 | 259 | | failedCount++; |
| | 0 | 260 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockUnarchiveItemStatus.Failed, |
| | 0 | 261 | | err, cancellationToken); |
| | 0 | 262 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 263 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 264 | | } |
| | 0 | 265 | | } |
| | | 266 | | |
| | 0 | 267 | | await _repository.UpdateExecutionCountersAsync(executionId, successCount, failedCount, |
| | 0 | 268 | | cancellationToken); |
| | | 269 | | |
| | 0 | 270 | | if (offset + BatchSize < clientItems.Count) |
| | | 271 | | { |
| | 0 | 272 | | await Task.Delay(DelayBetweenBatchesMs, cancellationToken); |
| | | 273 | | } |
| | 0 | 274 | | } |
| | 0 | 275 | | } |
| | | 276 | | |
| | 0 | 277 | | var finalStatus = failedCount == 0 |
| | 0 | 278 | | ? BitrixStockUnarchiveExecutionStatus.Success |
| | 0 | 279 | | : successCount == 0 && skippedCount == total |
| | 0 | 280 | | ? BitrixStockUnarchiveExecutionStatus.Success |
| | 0 | 281 | | : successCount == 0 |
| | 0 | 282 | | ? BitrixStockUnarchiveExecutionStatus.Failed |
| | 0 | 283 | | : BitrixStockUnarchiveExecutionStatus.PartialSuccess; |
| | | 284 | | |
| | 0 | 285 | | await _repository.UpdateExecutionCountersAsync(executionId, successCount, failedCount, cancellationToken); |
| | 0 | 286 | | await _repository.CompleteExecutionAsync(executionId, finalStatus, null, cancellationToken); |
| | | 287 | | |
| | 0 | 288 | | var report = BuildReportHtml(executionId, total, successCount, failedCount, skippedCount, finalStatus); |
| | 0 | 289 | | await SendLog($"Готово: успешно {successCount}, пропущено {skippedCount}, ошибок {failedCount}"); |
| | 0 | 290 | | if (sendHubComplete) |
| | | 291 | | { |
| | 0 | 292 | | await SendComplete(failedCount == 0, report); |
| | | 293 | | } |
| | 0 | 294 | | } |
| | 0 | 295 | | catch (Exception ex) |
| | | 296 | | { |
| | 0 | 297 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockUnarchiveExecutionStatus.Failed, ex.Message |
| | 0 | 298 | | cancellationToken); |
| | 0 | 299 | | if (sendHubComplete) |
| | | 300 | | { |
| | 0 | 301 | | await SendError(ex.Message); |
| | 0 | 302 | | await SendComplete(false, ex.Message); |
| | | 303 | | } |
| | 0 | 304 | | } |
| | | 305 | | finally |
| | | 306 | | { |
| | 0 | 307 | | HangfireDistributedLockHelper.SafeDispose(ref distLock, ref lockConnection); |
| | | 308 | | } |
| | 0 | 309 | | } |
| | | 310 | | |
| | | 311 | | public Task<(List<BitrixStockUnarchiveExecution> Items, int Total)> GetExecutionsPageAsync(int page, int pageSize, |
| | | 312 | | CancellationToken cancellationToken = default) => |
| | 0 | 313 | | _repository.GetExecutionsPageAsync(page, pageSize, cancellationToken); |
| | | 314 | | |
| | | 315 | | public Task<BitrixStockUnarchiveExecution?> GetExecutionDetailsAsync(long id, |
| | | 316 | | CancellationToken cancellationToken = default) => |
| | 0 | 317 | | _repository.GetExecutionByIdAsync(id, includeItems: true, cancellationToken); |
| | | 318 | | |
| | | 319 | | private static string FormatUnarchiveError(Exception ex) |
| | | 320 | | { |
| | 0 | 321 | | var msg = ex.Message; |
| | 0 | 322 | | if (msg.Contains("autoarchive_restore_failed", StringComparison.OrdinalIgnoreCase)) |
| | | 323 | | { |
| | 0 | 324 | | return "Превышен суточный лимит восстановления авто-архивных товаров (100 шт., обновление в 03:00 МСК)"; |
| | | 325 | | } |
| | | 326 | | |
| | 0 | 327 | | return msg; |
| | | 328 | | } |
| | | 329 | | |
| | | 330 | | private static string BuildReportHtml(long executionId, int total, int success, int failed, int skipped, |
| | | 331 | | string status) |
| | | 332 | | { |
| | 0 | 333 | | var sb = new StringBuilder(); |
| | 0 | 334 | | sb.Append($"<strong>Задание #{executionId}</strong> — {status}<br>"); |
| | 0 | 335 | | sb.Append($"Всего: {total}, успешно: {success}, пропущено: {skipped}, ошибок: {failed}"); |
| | 0 | 336 | | return sb.ToString(); |
| | | 337 | | } |
| | | 338 | | } |