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