| | | 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.ApiServices.OzonApi.Filters; |
| | | 11 | | using Services.DataServices; |
| | | 12 | | using Services.HangfireService; |
| | | 13 | | using Services.SignalRServices; |
| | | 14 | | using SlqStudio.Application.Services.EmailService; |
| | | 15 | | |
| | | 16 | | namespace Services.BitrixStockServices; |
| | | 17 | | |
| | | 18 | | public class BitrixStockClearJobService : IBitrixStockClearJobService |
| | | 19 | | { |
| | | 20 | | public const string ClearLockKey = "BitrixStock:ClearOzonStock"; |
| | | 21 | | private const int BatchSize = 100; |
| | | 22 | | private const int DelayBetweenBatchesMs = 400; |
| | | 23 | | |
| | | 24 | | private readonly IBitrixStockClearJobRepository _repository; |
| | | 25 | | private readonly OzonClientServices _ozonClientServices; |
| | | 26 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 27 | | private readonly IEmailService? _emailService; |
| | | 28 | | private readonly IHubContext<JobProgressHub> _jobProgressHub; |
| | | 29 | | private readonly IBitrixStockRunFileLogger? _runFileLogger; |
| | | 30 | | |
| | 0 | 31 | | public BitrixStockClearJobService( |
| | 0 | 32 | | IBitrixStockClearJobRepository repository, |
| | 0 | 33 | | OzonClientServices ozonClientServices, |
| | 0 | 34 | | IHttpClientFactory httpClientFactory, |
| | 0 | 35 | | IEmailService? emailService, |
| | 0 | 36 | | IHubContext<JobProgressHub> jobProgressHub, |
| | 0 | 37 | | IBitrixStockRunFileLogger? runFileLogger = null) |
| | | 38 | | { |
| | 0 | 39 | | _repository = repository; |
| | 0 | 40 | | _ozonClientServices = ozonClientServices; |
| | 0 | 41 | | _httpClientFactory = httpClientFactory; |
| | 0 | 42 | | _emailService = emailService; |
| | 0 | 43 | | _jobProgressHub = jobProgressHub; |
| | 0 | 44 | | _runFileLogger = runFileLogger; |
| | 0 | 45 | | } |
| | | 46 | | |
| | | 47 | | public async Task<BitrixStockClearExecution> CreateExecutionAsync( |
| | | 48 | | string jobId, |
| | | 49 | | IReadOnlyList<BitrixStockClearItemDto> items, |
| | | 50 | | string? userId, |
| | | 51 | | string? userName, |
| | | 52 | | string triggerType = "Manual", |
| | | 53 | | CancellationToken cancellationToken = default) |
| | | 54 | | { |
| | 0 | 55 | | var entities = items |
| | | 56 | | .Select((dto, index) => new BitrixStockClearItem |
| | | 57 | | { |
| | | 58 | | SortOrder = index, |
| | | 59 | | Article = dto.Article?.Trim(), |
| | | 60 | | OfferId = dto.OfferId?.Trim() ?? "", |
| | | 61 | | ProductId = dto.ProductId, |
| | | 62 | | WarehouseId = dto.WarehouseId, |
| | | 63 | | WarehouseName = dto.WarehouseName?.Trim(), |
| | | 64 | | OzonClient = dto.OzonClient?.Trim() ?? "", |
| | | 65 | | PreviousStock = dto.PreviousStock, |
| | | 66 | | TargetStock = 0, |
| | | 67 | | Status = BitrixStockClearItemStatus.Pending |
| | | 68 | | }) |
| | 0 | 69 | | .ToList(); |
| | | 70 | | |
| | 0 | 71 | | return await _repository.CreateExecutionAsync(jobId.Trim(), null, userId, userName, entities, triggerType, |
| | 0 | 72 | | cancellationToken); |
| | 0 | 73 | | } |
| | | 74 | | |
| | | 75 | | [Queue(HangfireQueueNames.Main)] |
| | | 76 | | public async Task ProcessClearAsync(long executionId, string jobId, bool sendHubComplete = true, |
| | | 77 | | CancellationToken cancellationToken = default) |
| | | 78 | | { |
| | 0 | 79 | | using var fileRun = _runFileLogger?.BeginRun(new BitrixStockRunContext(jobId, "LegacyClear", HangfireJobId: jobI |
| | 0 | 80 | | var hasHub = !string.IsNullOrWhiteSpace(jobId); |
| | 0 | 81 | | IDisposable? distLock = null; |
| | 0 | 82 | | IStorageConnection? lockConnection = null; |
| | | 83 | | |
| | | 84 | | async Task SendLog(string message) |
| | | 85 | | { |
| | 0 | 86 | | if (_runFileLogger != null) await _runFileLogger.ProcessAsync(message, cancellationToken: cancellationToken) |
| | 0 | 87 | | if (hasHub) |
| | | 88 | | { |
| | 0 | 89 | | await _jobProgressHub.Clients.Group(jobId).SendAsync("Log", message, cancellationToken); |
| | | 90 | | } |
| | 0 | 91 | | } |
| | | 92 | | |
| | | 93 | | async Task SendProgress(int current, int total, string statusText) |
| | | 94 | | { |
| | 0 | 95 | | if (hasHub) |
| | | 96 | | { |
| | 0 | 97 | | await _jobProgressHub.Clients.Group(jobId) |
| | 0 | 98 | | .SendAsync("Progress", current, total, statusText ?? "", cancellationToken); |
| | | 99 | | } |
| | 0 | 100 | | } |
| | | 101 | | |
| | | 102 | | async Task SendComplete(bool success, string report) |
| | | 103 | | { |
| | 0 | 104 | | if (hasHub) |
| | | 105 | | { |
| | 0 | 106 | | await _jobProgressHub.Clients.Group(jobId) |
| | 0 | 107 | | .SendAsync("Complete", success, report ?? "", cancellationToken); |
| | | 108 | | } |
| | 0 | 109 | | } |
| | | 110 | | |
| | | 111 | | async Task SendError(string message) |
| | | 112 | | { |
| | 0 | 113 | | if (hasHub) |
| | | 114 | | { |
| | 0 | 115 | | await _jobProgressHub.Clients.Group(jobId).SendAsync("Error", message, cancellationToken); |
| | | 116 | | } |
| | 0 | 117 | | } |
| | | 118 | | |
| | | 119 | | try |
| | | 120 | | { |
| | | 121 | | try |
| | | 122 | | { |
| | 0 | 123 | | lockConnection = JobStorage.Current.GetConnection(); |
| | 0 | 124 | | distLock = lockConnection.AcquireDistributedLock(ClearLockKey, TimeSpan.FromMilliseconds(1)); |
| | 0 | 125 | | } |
| | | 126 | | catch (DistributedLockTimeoutException) |
| | | 127 | | { |
| | | 128 | | const string msg = "Обнуление уже выполняется. Повторный запуск отменён."; |
| | 0 | 129 | | await SendLog(msg); |
| | 0 | 130 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockClearExecutionStatus.Failed, msg, |
| | 0 | 131 | | cancellationToken); |
| | 0 | 132 | | await SendComplete(false, msg); |
| | 0 | 133 | | return; |
| | | 134 | | } |
| | | 135 | | |
| | 0 | 136 | | var execution = await _repository.GetExecutionByIdAsync(executionId, includeItems: true, cancellationToken); |
| | 0 | 137 | | if (execution == null) |
| | | 138 | | { |
| | 0 | 139 | | await SendError($"Задание {executionId} не найдено"); |
| | 0 | 140 | | return; |
| | | 141 | | } |
| | | 142 | | |
| | | 143 | | var items = execution.Items.OrderBy(i => i.SortOrder).ToList(); |
| | 0 | 144 | | var total = items.Count; |
| | 0 | 145 | | if (total == 0) |
| | | 146 | | { |
| | 0 | 147 | | await SendLog("Нет позиций для обнуления"); |
| | 0 | 148 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockClearExecutionStatus.Success, null, |
| | 0 | 149 | | cancellationToken); |
| | 0 | 150 | | await SendComplete(true, "Нет позиций для обработки"); |
| | 0 | 151 | | return; |
| | | 152 | | } |
| | | 153 | | |
| | 0 | 154 | | await SendLog($"Старт обнуления: {total} позиций"); |
| | 0 | 155 | | var ozonClients = (await _ozonClientServices.GetOzonClients()) |
| | | 156 | | .Where(c => c.ClientType == ClientType.OZON) |
| | 0 | 157 | | .ToList(); |
| | | 158 | | |
| | 0 | 159 | | var successCount = 0; |
| | 0 | 160 | | var failedCount = 0; |
| | 0 | 161 | | var processed = 0; |
| | | 162 | | |
| | | 163 | | var groups = items.GroupBy(i => i.OzonClient, StringComparer.OrdinalIgnoreCase); |
| | 0 | 164 | | foreach (var clientGroup in groups) |
| | | 165 | | { |
| | 0 | 166 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 167 | | |
| | 0 | 168 | | var client = ozonClients.FirstOrDefault(c => |
| | 0 | 169 | | string.Equals(c.Name, clientGroup.Key, StringComparison.OrdinalIgnoreCase)); |
| | | 170 | | |
| | 0 | 171 | | if (client == null || |
| | 0 | 172 | | string.IsNullOrEmpty(client.DecryptClientId) || |
| | 0 | 173 | | string.IsNullOrEmpty(client.DecryptApiKey)) |
| | | 174 | | { |
| | 0 | 175 | | foreach (var item in clientGroup) |
| | | 176 | | { |
| | 0 | 177 | | processed++; |
| | 0 | 178 | | failedCount++; |
| | 0 | 179 | | var err = $"Клиент Ozon «{clientGroup.Key}» не найден или не настроен"; |
| | 0 | 180 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockClearItemStatus.Failed, err, |
| | 0 | 181 | | cancellationToken); |
| | 0 | 182 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 183 | | await SendProgress(processed, total, $"Ошибка клиента {clientGroup.Key}"); |
| | 0 | 184 | | } |
| | | 185 | | |
| | 0 | 186 | | continue; |
| | | 187 | | } |
| | | 188 | | |
| | 0 | 189 | | var apiManager = BitrixOzonApiFactory.Create(_httpClientFactory, _emailService, client); |
| | | 190 | | |
| | 0 | 191 | | var clientItems = clientGroup.ToList(); |
| | 0 | 192 | | for (var offset = 0; offset < clientItems.Count; offset += BatchSize) |
| | | 193 | | { |
| | 0 | 194 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 195 | | |
| | 0 | 196 | | var batchItems = clientItems.Skip(offset).Take(BatchSize).ToList(); |
| | 0 | 197 | | await SendLog( |
| | 0 | 198 | | $"Клиент {client.Name}: батч {offset / BatchSize + 1}, позиций {batchItems.Count}"); |
| | | 199 | | |
| | | 200 | | var stockPayload = batchItems.Select(i => new StockItemForUpdate |
| | | 201 | | { |
| | | 202 | | OfferId = i.OfferId, |
| | | 203 | | ProductId = i.ProductId, |
| | | 204 | | Stock = 0, |
| | | 205 | | WarehouseId = i.WarehouseId |
| | | 206 | | }).ToList(); |
| | | 207 | | |
| | 0 | 208 | | var handledInBatch = new HashSet<long>(); |
| | 0 | 209 | | var batchOk = await TryUpdateBatchAsync(apiManager, stockPayload, batchItems, async (item, error) => |
| | 0 | 210 | | { |
| | 0 | 211 | | handledInBatch.Add(item.Id); |
| | 0 | 212 | | processed++; |
| | 0 | 213 | | failedCount++; |
| | 0 | 214 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockClearItemStatus.Failed, error, |
| | 0 | 215 | | cancellationToken); |
| | 0 | 216 | | await SendLog($"✗ {item.Article ?? item.OfferId} ({item.WarehouseName ?? item.WarehouseId.ToStri |
| | 0 | 217 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 218 | | }, async (item) => |
| | 0 | 219 | | { |
| | 0 | 220 | | handledInBatch.Add(item.Id); |
| | 0 | 221 | | processed++; |
| | 0 | 222 | | successCount++; |
| | 0 | 223 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockClearItemStatus.Success, null, |
| | 0 | 224 | | cancellationToken); |
| | 0 | 225 | | await SendLog($"✓ {item.Article ?? item.OfferId} → 0 ({item.WarehouseName ?? item.WarehouseId.To |
| | 0 | 226 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 227 | | }, cancellationToken); |
| | | 228 | | |
| | 0 | 229 | | if (!batchOk) |
| | | 230 | | { |
| | 0 | 231 | | foreach (var item in batchItems) |
| | | 232 | | { |
| | 0 | 233 | | if (handledInBatch.Contains(item.Id)) |
| | | 234 | | { |
| | | 235 | | continue; |
| | | 236 | | } |
| | | 237 | | |
| | 0 | 238 | | var single = new List<StockItemForUpdate> |
| | 0 | 239 | | { |
| | 0 | 240 | | new() |
| | 0 | 241 | | { |
| | 0 | 242 | | OfferId = item.OfferId, |
| | 0 | 243 | | ProductId = item.ProductId, |
| | 0 | 244 | | Stock = 0, |
| | 0 | 245 | | WarehouseId = item.WarehouseId |
| | 0 | 246 | | } |
| | 0 | 247 | | }; |
| | | 248 | | |
| | | 249 | | try |
| | | 250 | | { |
| | 0 | 251 | | var singleResult = await apiManager.UpdateProductStocks(single); |
| | 0 | 252 | | var row = singleResult?.Result?.FirstOrDefault(); |
| | 0 | 253 | | if (row != null && row.Updated && (row.Errors == null || !row.Errors.Any())) |
| | | 254 | | { |
| | 0 | 255 | | processed++; |
| | 0 | 256 | | successCount++; |
| | 0 | 257 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockClearItemStatus.Success, |
| | 0 | 258 | | null, cancellationToken); |
| | 0 | 259 | | await SendLog( |
| | 0 | 260 | | $"✓ {item.Article ?? item.OfferId} → 0 (повтор по одной)"); |
| | | 261 | | } |
| | | 262 | | else |
| | | 263 | | { |
| | 0 | 264 | | var err = FormatStockErrors(row); |
| | 0 | 265 | | processed++; |
| | 0 | 266 | | failedCount++; |
| | 0 | 267 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockClearItemStatus.Failed, |
| | 0 | 268 | | err, cancellationToken); |
| | 0 | 269 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {err}"); |
| | 0 | 270 | | } |
| | 0 | 271 | | } |
| | 0 | 272 | | catch (Exception ex) |
| | | 273 | | { |
| | 0 | 274 | | processed++; |
| | 0 | 275 | | failedCount++; |
| | 0 | 276 | | await _repository.UpdateItemResultAsync(item.Id, BitrixStockClearItemStatus.Failed, |
| | 0 | 277 | | ex.Message, cancellationToken); |
| | 0 | 278 | | await SendLog($"✗ {item.Article ?? item.OfferId}: {ex.Message}"); |
| | 0 | 279 | | } |
| | | 280 | | |
| | 0 | 281 | | await SendProgress(processed, total, item.OfferId); |
| | 0 | 282 | | await Task.Delay(200, cancellationToken); |
| | 0 | 283 | | } |
| | | 284 | | } |
| | | 285 | | |
| | 0 | 286 | | await _repository.UpdateExecutionCountersAsync(executionId, successCount, failedCount, |
| | 0 | 287 | | cancellationToken); |
| | | 288 | | |
| | 0 | 289 | | if (offset + BatchSize < clientItems.Count) |
| | | 290 | | { |
| | 0 | 291 | | await Task.Delay(DelayBetweenBatchesMs, cancellationToken); |
| | | 292 | | } |
| | 0 | 293 | | } |
| | 0 | 294 | | } |
| | | 295 | | |
| | 0 | 296 | | var finalStatus = failedCount == 0 |
| | 0 | 297 | | ? BitrixStockClearExecutionStatus.Success |
| | 0 | 298 | | : successCount == 0 |
| | 0 | 299 | | ? BitrixStockClearExecutionStatus.Failed |
| | 0 | 300 | | : BitrixStockClearExecutionStatus.PartialSuccess; |
| | | 301 | | |
| | 0 | 302 | | await _repository.UpdateExecutionCountersAsync(executionId, successCount, failedCount, cancellationToken); |
| | 0 | 303 | | await _repository.CompleteExecutionAsync(executionId, finalStatus, null, cancellationToken); |
| | | 304 | | |
| | 0 | 305 | | var report = BuildReportHtml(executionId, total, successCount, failedCount, finalStatus); |
| | 0 | 306 | | await SendLog($"Готово: успешно {successCount}, ошибок {failedCount}"); |
| | 0 | 307 | | if (_runFileLogger != null) await _runFileLogger.CompleteAsync(failedCount == 0, failedCount == 0 ? null : $ |
| | 0 | 308 | | if (sendHubComplete) |
| | | 309 | | { |
| | 0 | 310 | | await SendComplete(failedCount == 0, report); |
| | | 311 | | } |
| | 0 | 312 | | } |
| | 0 | 313 | | catch (Exception ex) |
| | | 314 | | { |
| | 0 | 315 | | if (_runFileLogger != null) await _runFileLogger.CompleteAsync(false, ex.Message, CancellationToken.None); |
| | 0 | 316 | | await _repository.CompleteExecutionAsync(executionId, BitrixStockClearExecutionStatus.Failed, ex.Message, |
| | 0 | 317 | | cancellationToken); |
| | 0 | 318 | | if (sendHubComplete) |
| | | 319 | | { |
| | 0 | 320 | | await SendError(ex.Message); |
| | | 321 | | } |
| | | 322 | | |
| | 0 | 323 | | await SendLog($"Критическая ошибка: {ex.Message}"); |
| | 0 | 324 | | if (sendHubComplete) |
| | | 325 | | { |
| | 0 | 326 | | await SendComplete(false, ex.Message); |
| | | 327 | | } |
| | | 328 | | |
| | 0 | 329 | | throw; |
| | 0 | 330 | | } |
| | | 331 | | finally |
| | | 332 | | { |
| | 0 | 333 | | HangfireDistributedLockHelper.SafeDispose(ref distLock, ref lockConnection); |
| | | 334 | | } |
| | 0 | 335 | | } |
| | | 336 | | |
| | | 337 | | public Task<(List<BitrixStockClearExecution> Items, int Total)> GetExecutionsPageAsync(int page, int pageSize, |
| | | 338 | | CancellationToken cancellationToken = default) => |
| | 0 | 339 | | _repository.GetExecutionsPageAsync(page, pageSize, cancellationToken); |
| | | 340 | | |
| | | 341 | | public Task<BitrixStockClearExecution?> GetExecutionDetailsAsync(long id, |
| | | 342 | | CancellationToken cancellationToken = default) => |
| | 0 | 343 | | _repository.GetExecutionByIdAsync(id, includeItems: true, cancellationToken); |
| | | 344 | | |
| | | 345 | | private static async Task<bool> TryUpdateBatchAsync( |
| | | 346 | | OzonApiDataManager apiManager, |
| | | 347 | | List<StockItemForUpdate> stockPayload, |
| | | 348 | | List<BitrixStockClearItem> batchItems, |
| | | 349 | | Func<BitrixStockClearItem, string, Task> onFailed, |
| | | 350 | | Func<BitrixStockClearItem, Task> onSuccess, |
| | | 351 | | CancellationToken cancellationToken) |
| | | 352 | | { |
| | | 353 | | try |
| | | 354 | | { |
| | 0 | 355 | | var result = await apiManager.UpdateProductStocks(stockPayload); |
| | 0 | 356 | | if (result?.Result == null || result.Result.Count == 0) |
| | | 357 | | { |
| | 0 | 358 | | return false; |
| | | 359 | | } |
| | | 360 | | |
| | 0 | 361 | | var byKey = batchItems.ToDictionary( |
| | | 362 | | i => $"{i.ProductId}_{i.WarehouseId}", |
| | | 363 | | i => i); |
| | | 364 | | |
| | 0 | 365 | | var allOk = true; |
| | 0 | 366 | | foreach (var row in result.Result) |
| | | 367 | | { |
| | 0 | 368 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 0 | 369 | | var key = $"{row.ProductId}_{row.WarehouseId}"; |
| | 0 | 370 | | if (!byKey.TryGetValue(key, out var item)) |
| | | 371 | | { |
| | | 372 | | continue; |
| | | 373 | | } |
| | | 374 | | |
| | 0 | 375 | | if (row.Updated && (row.Errors == null || !row.Errors.Any())) |
| | | 376 | | { |
| | 0 | 377 | | await onSuccess(item); |
| | | 378 | | } |
| | | 379 | | else |
| | | 380 | | { |
| | 0 | 381 | | allOk = false; |
| | 0 | 382 | | await onFailed(item, FormatStockErrors(row)); |
| | | 383 | | } |
| | | 384 | | } |
| | | 385 | | |
| | 0 | 386 | | if (batchItems.Any(i => !byKey.ContainsKey($"{i.ProductId}_{i.WarehouseId}"))) |
| | | 387 | | { |
| | 0 | 388 | | allOk = false; |
| | | 389 | | } |
| | | 390 | | |
| | 0 | 391 | | return allOk; |
| | | 392 | | } |
| | 0 | 393 | | catch |
| | | 394 | | { |
| | 0 | 395 | | return false; |
| | | 396 | | } |
| | 0 | 397 | | } |
| | | 398 | | |
| | | 399 | | private static string FormatStockErrors(UpdateStockResult? row) |
| | | 400 | | { |
| | 0 | 401 | | if (row?.Errors != null && row.Errors.Any()) |
| | | 402 | | { |
| | 0 | 403 | | return string.Join("; ", row.Errors.Select(e => e.Message ?? e.Code ?? "error")); |
| | | 404 | | } |
| | | 405 | | |
| | 0 | 406 | | return row?.Updated == true ? string.Empty : "Ozon не обновил остаток"; |
| | | 407 | | } |
| | | 408 | | |
| | | 409 | | private static string BuildReportHtml(long executionId, int total, int success, int failed, string status) |
| | | 410 | | { |
| | 0 | 411 | | var sb = new StringBuilder(); |
| | 0 | 412 | | sb.Append("<div><strong>Итог обнуления</strong><br/>"); |
| | 0 | 413 | | sb.Append($"Задание #{executionId}, статус: {status}<br/>"); |
| | 0 | 414 | | sb.Append($"Всего: {total}, успешно: {success}, ошибок: {failed}</div>"); |
| | 0 | 415 | | return sb.ToString(); |
| | | 416 | | } |
| | | 417 | | } |