| | | 1 | | using Hangfire; |
| | | 2 | | using Microsoft.AspNetCore.SignalR; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | using OzonDomains; |
| | | 6 | | using OzonDomains.Models; |
| | | 7 | | using OzonRepositories.Context; |
| | | 8 | | using Services.ApiServices; |
| | | 9 | | using Services.ApiServices._1CApi; |
| | | 10 | | using Services.ApiServices._1CApi.Models; |
| | | 11 | | using Services.ApiServices._1CApi.OData; |
| | | 12 | | using Services.DataServices; |
| | | 13 | | using Services.SignalRServices; |
| | | 14 | | using Services.HangfireService; |
| | | 15 | | using Services.TransactionUtilsServices; |
| | | 16 | | |
| | | 17 | | namespace Services.BackgroundJobsServices; |
| | | 18 | | |
| | | 19 | | public interface IAutomatedTransactionProcessingService |
| | | 20 | | { |
| | | 21 | | Task ProcessShippedToCommissionerAsync(int scheduleId, CancellationToken cancellationToken = default); |
| | | 22 | | Task ProcessShippedToCommissionerManualAsync(int ozonClientId, int daysBack, string? jobId = null, CancellationToken |
| | | 23 | | Task ProcessShippedToCommissionerScheduledRetryAsync(int scheduleId, int retryAttempt, CancellationToken cancellatio |
| | | 24 | | Task ProcessShippedToCommissionerManualRetryAsync(int ozonClientId, int daysBack, string? jobId, int retryAttempt, C |
| | | 25 | | Task ProcessCustomerReturnAsync(int scheduleId, CancellationToken cancellationToken = default); |
| | | 26 | | Task ProcessCustomerReturnManualAsync(int ozonClientId, int daysBack, string? jobId = null, CancellationToken cancel |
| | | 27 | | Task ProcessCustomerReturnScheduledRetryAsync(int scheduleId, int retryAttempt, CancellationToken cancellationToken |
| | | 28 | | Task ProcessCustomerReturnManualRetryAsync(int ozonClientId, int daysBack, string? jobId, int retryAttempt, Cancella |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public class AutomatedTransactionProcessingService : IAutomatedTransactionProcessingService |
| | | 32 | | { |
| | | 33 | | private readonly IBackgroundJobLoggingService _loggingService; |
| | | 34 | | private readonly IBackgroundJobScheduleService _scheduleService; |
| | | 35 | | private readonly ITransactionJobRetryScheduler _retryScheduler; |
| | | 36 | | private readonly IOzonReportLoaderService _reportLoader; |
| | | 37 | | private readonly OrdersDataServices _orderServices; |
| | | 38 | | private readonly TransactionDataServices _transactionDataServices; |
| | | 39 | | private readonly AppStatusDataServices _appStatusServices; |
| | | 40 | | private readonly TransactionManager _transactionManager; |
| | | 41 | | private readonly OneCTransferManager _oneCTransferManager; |
| | | 42 | | private readonly IStatusTransitionHistoryService _statusTransitionHistoryService; |
| | | 43 | | private readonly StatusTransitionDataServices _statusTransitionDataServices; |
| | | 44 | | private readonly WarehouseSelectionResolver _warehouseSelectionResolver; |
| | | 45 | | private readonly IHubContext<JobProgressHub> _hubContext; |
| | | 46 | | private readonly ApplicationDbContext _context; |
| | | 47 | | private readonly IServiceProvider _serviceProvider; |
| | 0 | 48 | | private static readonly TimeZoneInfo RussianTimeZone = RussianTimeZoneHelper.Zone; |
| | | 49 | | private const string SystemUserName = "Система"; |
| | | 50 | | private const string CommissionerStatusName = "Отгружен комиссионеру"; |
| | | 51 | | private const string CustomerReturnStatusName = "Возврат покупателя"; |
| | | 52 | | private const string SellerStatusName = "Отгружен реализатором"; |
| | | 53 | | private const string ZasylKey = "Засыл"; |
| | | 54 | | private const int OrderProcessingBatchSize = 200; |
| | | 55 | | private const int MaxExecutionErrorMessageLength = 16000; |
| | | 56 | | |
| | | 57 | | private sealed class CommissionerWarehouseBatchResult |
| | | 58 | | { |
| | 0 | 59 | | public List<Order> ReadyOrders { get; init; } = []; |
| | 0 | 60 | | public Dictionary<int, string> WarehouseByOrderId { get; init; } = new(); |
| | 0 | 61 | | public int SkippedCount { get; init; } |
| | 0 | 62 | | public List<string> FailureDetails { get; init; } = []; |
| | | 63 | | } |
| | | 64 | | |
| | | 65 | | internal static bool IsAlreadyShippedToCommissioner(Order order) => |
| | 4 | 66 | | string.Equals(order.AppStatus?.Name, CommissionerStatusName, StringComparison.OrdinalIgnoreCase); |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Как в ручной отгрузке комиссионеру: заказ уже «Отгружен реализатором» — только смена статуса, без документа и 1С |
| | | 70 | | /// </summary> |
| | | 71 | | internal static bool IsStatusOnlyCommissionerChange(Order order) => |
| | 4 | 72 | | string.Equals(order.AppStatus?.Name, SellerStatusName, StringComparison.OrdinalIgnoreCase); |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Определяет, подходит ли заказ для автоматической обработки. |
| | | 76 | | /// Вынесено из FilterEligibleOrdersAsync для изолированного тестирования. |
| | | 77 | | /// </summary> |
| | | 78 | | internal static bool IsEligibleForAutomatedProcessing(Order order) => |
| | 6 | 79 | | order.AppStatus != null && |
| | 6 | 80 | | !string.Equals(order.AppStatus.Name, CommissionerStatusName, StringComparison.OrdinalIgnoreCase) && |
| | 6 | 81 | | !string.Equals(order.AppStatus.Name, "Отменен покупателем", StringComparison.OrdinalIgnoreCase); |
| | | 82 | | |
| | 0 | 83 | | public AutomatedTransactionProcessingService( |
| | 0 | 84 | | IBackgroundJobLoggingService loggingService, |
| | 0 | 85 | | IBackgroundJobScheduleService scheduleService, |
| | 0 | 86 | | ITransactionJobRetryScheduler retryScheduler, |
| | 0 | 87 | | IOzonReportLoaderService reportLoader, |
| | 0 | 88 | | OrdersDataServices orderServices, |
| | 0 | 89 | | TransactionDataServices transactionDataServices, |
| | 0 | 90 | | AppStatusDataServices appStatusServices, |
| | 0 | 91 | | TransactionManager transactionManager, |
| | 0 | 92 | | OneCTransferManager oneCTransferManager, |
| | 0 | 93 | | IStatusTransitionHistoryService statusTransitionHistoryService, |
| | 0 | 94 | | StatusTransitionDataServices statusTransitionDataServices, |
| | 0 | 95 | | WarehouseSelectionResolver warehouseSelectionResolver, |
| | 0 | 96 | | IHubContext<JobProgressHub> hubContext, |
| | 0 | 97 | | ApplicationDbContext context, |
| | 0 | 98 | | IServiceProvider serviceProvider) |
| | | 99 | | { |
| | 0 | 100 | | _loggingService = loggingService; |
| | 0 | 101 | | _scheduleService = scheduleService; |
| | 0 | 102 | | _retryScheduler = retryScheduler; |
| | 0 | 103 | | _reportLoader = reportLoader; |
| | 0 | 104 | | _orderServices = orderServices; |
| | 0 | 105 | | _transactionDataServices = transactionDataServices; |
| | 0 | 106 | | _appStatusServices = appStatusServices; |
| | 0 | 107 | | _transactionManager = transactionManager; |
| | 0 | 108 | | _oneCTransferManager = oneCTransferManager; |
| | 0 | 109 | | _statusTransitionHistoryService = statusTransitionHistoryService; |
| | 0 | 110 | | _statusTransitionDataServices = statusTransitionDataServices; |
| | 0 | 111 | | _warehouseSelectionResolver = warehouseSelectionResolver; |
| | 0 | 112 | | _hubContext = hubContext; |
| | 0 | 113 | | _context = context; |
| | 0 | 114 | | _serviceProvider = serviceProvider; |
| | 0 | 115 | | } |
| | | 116 | | |
| | | 117 | | [Queue(HangfireQueueNames.Main)] |
| | | 118 | | public async Task ProcessShippedToCommissionerAsync(int scheduleId, CancellationToken cancellationToken = default) |
| | | 119 | | { |
| | 0 | 120 | | var schedule = await _scheduleService.GetScheduleByIdAsync(scheduleId, cancellationToken); |
| | 0 | 121 | | if (schedule == null || !schedule.IsActive) |
| | | 122 | | { |
| | 0 | 123 | | Console.WriteLine($"[AutomatedTransactionProcessing] Schedule {scheduleId} not found or inactive"); |
| | 0 | 124 | | return; |
| | | 125 | | } |
| | | 126 | | |
| | 0 | 127 | | if (!schedule.OzonClientId.HasValue) |
| | | 128 | | { |
| | 0 | 129 | | Console.WriteLine($"[AutomatedTransactionProcessing] Schedule {scheduleId} has no OzonClientId"); |
| | 0 | 130 | | return; |
| | | 131 | | } |
| | | 132 | | |
| | 0 | 133 | | schedule.LastRunTime = DateTime.UtcNow; |
| | 0 | 134 | | await _context.SaveChangesAsync(cancellationToken); |
| | | 135 | | |
| | 0 | 136 | | await ProcessShippedToCommissionerInternalAsync( |
| | 0 | 137 | | schedule.OzonClientId.Value, |
| | 0 | 138 | | schedule.DaysBack, |
| | 0 | 139 | | scheduleId, |
| | 0 | 140 | | "Scheduled", |
| | 0 | 141 | | null, |
| | 0 | 142 | | retryAttempt: 0, |
| | 0 | 143 | | cancellationToken); |
| | 0 | 144 | | } |
| | | 145 | | |
| | | 146 | | [Queue(HangfireQueueNames.Main)] |
| | | 147 | | public async Task ProcessShippedToCommissionerManualAsync(int ozonClientId, int daysBack, string? jobId = null, Canc |
| | | 148 | | { |
| | 0 | 149 | | await ProcessShippedToCommissionerInternalAsync(ozonClientId, daysBack, null, "Manual", jobId, 0, cancellationTo |
| | 0 | 150 | | } |
| | | 151 | | |
| | | 152 | | [Queue(HangfireQueueNames.Main)] |
| | | 153 | | public async Task ProcessShippedToCommissionerScheduledRetryAsync(int scheduleId, int retryAttempt, CancellationToke |
| | | 154 | | { |
| | 0 | 155 | | var schedule = await _scheduleService.GetScheduleByIdAsync(scheduleId, cancellationToken); |
| | 0 | 156 | | if (schedule == null || !schedule.IsActive || !schedule.OzonClientId.HasValue) |
| | 0 | 157 | | return; |
| | | 158 | | |
| | 0 | 159 | | schedule.LastRunTime = DateTime.UtcNow; |
| | 0 | 160 | | await _context.SaveChangesAsync(cancellationToken); |
| | | 161 | | |
| | 0 | 162 | | await ProcessShippedToCommissionerInternalAsync( |
| | 0 | 163 | | schedule.OzonClientId.Value, |
| | 0 | 164 | | schedule.DaysBack, |
| | 0 | 165 | | scheduleId, |
| | 0 | 166 | | "Retry", |
| | 0 | 167 | | null, |
| | 0 | 168 | | retryAttempt, |
| | 0 | 169 | | cancellationToken); |
| | 0 | 170 | | } |
| | | 171 | | |
| | | 172 | | [Queue(HangfireQueueNames.Main)] |
| | | 173 | | public async Task ProcessShippedToCommissionerManualRetryAsync( |
| | | 174 | | int ozonClientId, int daysBack, string? jobId, int retryAttempt, CancellationToken cancellationToken = default) |
| | | 175 | | { |
| | 0 | 176 | | await ProcessShippedToCommissionerInternalAsync(ozonClientId, daysBack, null, "Retry", jobId, retryAttempt, canc |
| | 0 | 177 | | } |
| | | 178 | | |
| | | 179 | | [Queue(HangfireQueueNames.Main)] |
| | | 180 | | public async Task ProcessCustomerReturnAsync(int scheduleId, CancellationToken cancellationToken = default) |
| | | 181 | | { |
| | 0 | 182 | | var schedule = await _scheduleService.GetScheduleByIdAsync(scheduleId, cancellationToken); |
| | 0 | 183 | | if (schedule == null || !schedule.IsActive) |
| | 0 | 184 | | return; |
| | | 185 | | |
| | 0 | 186 | | if (!schedule.OzonClientId.HasValue) |
| | 0 | 187 | | return; |
| | | 188 | | |
| | 0 | 189 | | schedule.LastRunTime = DateTime.UtcNow; |
| | 0 | 190 | | await _context.SaveChangesAsync(cancellationToken); |
| | | 191 | | |
| | 0 | 192 | | await ProcessCustomerReturnInternalAsync( |
| | 0 | 193 | | schedule.OzonClientId.Value, |
| | 0 | 194 | | schedule.DaysBack, |
| | 0 | 195 | | scheduleId, |
| | 0 | 196 | | "Scheduled", |
| | 0 | 197 | | null, |
| | 0 | 198 | | retryAttempt: 0, |
| | 0 | 199 | | cancellationToken); |
| | 0 | 200 | | } |
| | | 201 | | |
| | | 202 | | [Queue(HangfireQueueNames.Main)] |
| | | 203 | | public async Task ProcessCustomerReturnManualAsync(int ozonClientId, int daysBack, string? jobId = null, Cancellatio |
| | | 204 | | { |
| | 0 | 205 | | await ProcessCustomerReturnInternalAsync(ozonClientId, daysBack, null, "Manual", jobId, 0, cancellationToken); |
| | 0 | 206 | | } |
| | | 207 | | |
| | | 208 | | [Queue(HangfireQueueNames.Main)] |
| | | 209 | | public async Task ProcessCustomerReturnScheduledRetryAsync(int scheduleId, int retryAttempt, CancellationToken cance |
| | | 210 | | { |
| | 0 | 211 | | var schedule = await _scheduleService.GetScheduleByIdAsync(scheduleId, cancellationToken); |
| | 0 | 212 | | if (schedule == null || !schedule.IsActive || !schedule.OzonClientId.HasValue) |
| | 0 | 213 | | return; |
| | | 214 | | |
| | 0 | 215 | | schedule.LastRunTime = DateTime.UtcNow; |
| | 0 | 216 | | await _context.SaveChangesAsync(cancellationToken); |
| | | 217 | | |
| | 0 | 218 | | await ProcessCustomerReturnInternalAsync( |
| | 0 | 219 | | schedule.OzonClientId.Value, |
| | 0 | 220 | | schedule.DaysBack, |
| | 0 | 221 | | scheduleId, |
| | 0 | 222 | | "Retry", |
| | 0 | 223 | | null, |
| | 0 | 224 | | retryAttempt, |
| | 0 | 225 | | cancellationToken); |
| | 0 | 226 | | } |
| | | 227 | | |
| | | 228 | | [Queue(HangfireQueueNames.Main)] |
| | | 229 | | public async Task ProcessCustomerReturnManualRetryAsync( |
| | | 230 | | int ozonClientId, int daysBack, string? jobId, int retryAttempt, CancellationToken cancellationToken = default) |
| | | 231 | | { |
| | 0 | 232 | | await ProcessCustomerReturnInternalAsync(ozonClientId, daysBack, null, "Retry", jobId, retryAttempt, cancellatio |
| | 0 | 233 | | } |
| | | 234 | | |
| | | 235 | | private async Task ProcessCustomerReturnInternalAsync( |
| | | 236 | | int ozonClientId, |
| | | 237 | | int daysBack, |
| | | 238 | | int? scheduleId, |
| | | 239 | | string triggerType, |
| | | 240 | | string? jobId, |
| | | 241 | | int retryAttempt, |
| | | 242 | | CancellationToken cancellationToken = default) |
| | | 243 | | { |
| | 0 | 244 | | var executionId = await _loggingService.StartExecutionAsync(scheduleId, "CustomerReturn", triggerType, cancellat |
| | | 245 | | |
| | | 246 | | try |
| | | 247 | | { |
| | 0 | 248 | | if (retryAttempt > 0) |
| | | 249 | | { |
| | 0 | 250 | | await SendLogAsync(jobId, $"↻ Повторная попытка {retryAttempt}/{TransactionJobRetryPolicy.MaxRetryAttemp |
| | | 251 | | } |
| | | 252 | | |
| | 0 | 253 | | var step1Id = await _loggingService.StartStepAsync(executionId, 1, "LoadReport", new { ozonClientId, daysBac |
| | 0 | 254 | | await SendLogAsync(jobId, "Шаг 1/7: Загрузка отчёта возвратов..."); |
| | 0 | 255 | | var reportPeriods = BuildReportPeriods(daysBack); |
| | 0 | 256 | | await SendLogAsync(jobId, |
| | 0 | 257 | | $"Загрузка отчёта (API): {reportPeriods.DownloadFrom:dd.MM.yyyy} — {reportPeriods.DownloadTo:dd.MM.yyyy} |
| | 0 | 258 | | await SendLogAsync(jobId, |
| | 0 | 259 | | $"Отбор строк «{ReportDeliveryDateFilter.ReturnsStatusDateColumnName}»: {reportPeriods.FilterDateKeys[0] |
| | 0 | 260 | | var oneCOperationDate = reportPeriods.TargetDay; |
| | 0 | 261 | | var (_, fileName, shipmentNumbers) = await _reportLoader.LoadAndParseReturnsReportAsync( |
| | 0 | 262 | | ozonClientId, |
| | 0 | 263 | | reportPeriods.DownloadFrom, |
| | 0 | 264 | | reportPeriods.DownloadTo, |
| | 0 | 265 | | reportPeriods.FilterDateKeys, |
| | 0 | 266 | | executionId, |
| | 0 | 267 | | step1Id, |
| | 0 | 268 | | _loggingService, |
| | 0 | 269 | | cancellationToken); |
| | 0 | 270 | | await SendLogAsync(jobId, $"✓ Из отчёта {fileName}: {shipmentNumbers.Count} отправлений"); |
| | 0 | 271 | | await _loggingService.CompleteStepAsync(step1Id, new { shipmentsCount = shipmentNumbers.Count, fileName }, c |
| | 0 | 272 | | await _loggingService.UpdateExecutionStatsAsync(executionId, totalOrders: shipmentNumbers.Count, cancellatio |
| | | 273 | | |
| | 0 | 274 | | var step2Id = await _loggingService.StartStepAsync(executionId, 2, "MatchOrders", new { shipmentsCount = shi |
| | 0 | 275 | | await SendLogAsync(jobId, "Шаг 2/7: Сопоставление заказов по отправлениям..."); |
| | 0 | 276 | | var matchedOrders = await MatchOrdersByShipmentAsync(executionId, step2Id, ozonClientId, shipmentNumbers, ca |
| | 0 | 277 | | await _loggingService.CompleteStepAsync(step2Id, new { matchedCount = matchedOrders.Count }, cancellationTok |
| | 0 | 278 | | await _loggingService.UpdateExecutionStatsAsync(executionId, matchedOrders: matchedOrders.Count, cancellatio |
| | | 279 | | |
| | 0 | 280 | | var step3Id = await _loggingService.StartStepAsync(executionId, 3, "ExcludeProcessedOrders", new { beforeCou |
| | 0 | 281 | | var skippedOrders = matchedOrders |
| | 0 | 282 | | .Where(o => string.Equals(o.AppStatus?.Name, CustomerReturnStatusName, StringComparison.OrdinalIgnoreCas |
| | 0 | 283 | | .ToList(); |
| | 0 | 284 | | var eligibleOrders = matchedOrders |
| | 0 | 285 | | .Where(o => !string.Equals(o.AppStatus?.Name, CustomerReturnStatusName, StringComparison.OrdinalIgnoreCa |
| | 0 | 286 | | .ToList(); |
| | | 287 | | |
| | 0 | 288 | | foreach (var skippedOrder in skippedOrders) |
| | | 289 | | { |
| | 0 | 290 | | var match = await _context.BackgroundOrderMatches |
| | 0 | 291 | | .Where(m => m.ExecutionId == executionId && m.OrderId == skippedOrder.Id) |
| | 0 | 292 | | .OrderByDescending(m => m.CreatedAt) |
| | 0 | 293 | | .FirstOrDefaultAsync(cancellationToken); |
| | | 294 | | |
| | 0 | 295 | | if (match != null) |
| | | 296 | | { |
| | 0 | 297 | | match.IsEligibleForProcessing = false; |
| | 0 | 298 | | match.RejectionReason = "Уже имеет статус 'Возврат покупателя' — пропущен"; |
| | | 299 | | } |
| | | 300 | | |
| | 0 | 301 | | await _loggingService.LogTransactionResultAsync( |
| | 0 | 302 | | executionId, |
| | 0 | 303 | | step3Id, |
| | 0 | 304 | | match?.Id, |
| | 0 | 305 | | skippedOrder.Id, |
| | 0 | 306 | | null, |
| | 0 | 307 | | null, |
| | 0 | 308 | | "Skipped", |
| | 0 | 309 | | "Уже имеет статус 'Возврат покупателя' — пропущен из фоновой обработки", |
| | 0 | 310 | | cancellationToken); |
| | 0 | 311 | | } |
| | | 312 | | |
| | 0 | 313 | | if (skippedOrders.Any()) |
| | 0 | 314 | | await _context.SaveChangesAsync(cancellationToken); |
| | | 315 | | |
| | 0 | 316 | | await _loggingService.CompleteStepAsync(step3Id, new { beforeCount = matchedOrders.Count, afterCount = eligi |
| | | 317 | | |
| | 0 | 318 | | var step4Id = await _loggingService.StartStepAsync(executionId, 4, "ResolveWarehouses", new { eligibleCount |
| | 0 | 319 | | await SendLogAsync(jobId, "Шаг 4/7: Подстановка складов (отправитель / получатель)..."); |
| | 0 | 320 | | var (warehouseReadyOrders, warehouseSkippedCount, senderWarehouse, recipientByOrderId) = |
| | 0 | 321 | | await ResolveCustomerReturnWarehousesAsync(executionId, step4Id, eligibleOrders, jobId, cancellationToke |
| | 0 | 322 | | await _loggingService.CompleteStepAsync(step4Id, |
| | 0 | 323 | | new { readyCount = warehouseReadyOrders.Count, skippedCount = warehouseSkippedCount, senderWarehouse }, |
| | 0 | 324 | | cancellationToken); |
| | 0 | 325 | | await SendLogAsync(jobId, $"✓ К обработке после складов: {warehouseReadyOrders.Count}, пропущено: {warehouse |
| | 0 | 326 | | await SendProgressAsync(jobId, 55, "Склады определены"); |
| | | 327 | | |
| | 0 | 328 | | var step5Id = await _loggingService.StartStepAsync(executionId, 5, "CreateTransactions", new { readyCount = |
| | 0 | 329 | | await SendLogAsync(jobId, "Шаг 5/7: Проведение в 1С и создание транзакций..."); |
| | 0 | 330 | | var (processedCount, failedCount) = await ProcessCustomerReturnWithOneCAsync( |
| | 0 | 331 | | executionId, |
| | 0 | 332 | | step5Id, |
| | 0 | 333 | | warehouseReadyOrders, |
| | 0 | 334 | | senderWarehouse, |
| | 0 | 335 | | recipientByOrderId, |
| | 0 | 336 | | oneCOperationDate, |
| | 0 | 337 | | scheduleId, |
| | 0 | 338 | | jobId, |
| | 0 | 339 | | cancellationToken); |
| | 0 | 340 | | await _loggingService.CompleteStepAsync(step5Id, new { processedCount, failedCount }, cancellationToken); |
| | 0 | 341 | | await _loggingService.UpdateExecutionStatsAsync( |
| | 0 | 342 | | executionId, |
| | 0 | 343 | | processedOrders: processedCount + failedCount, |
| | 0 | 344 | | successfulOrders: processedCount, |
| | 0 | 345 | | failedOrders: failedCount, |
| | 0 | 346 | | cancellationToken: cancellationToken); |
| | 0 | 347 | | await SendLogAsync(jobId, $"✓ Проведено: {processedCount}, ошибок: {failedCount}"); |
| | 0 | 348 | | await SendProgressAsync(jobId, 90, "Проведение завершено"); |
| | | 349 | | |
| | 0 | 350 | | var step6Id = await _loggingService.StartStepAsync(executionId, 6, "Finalize", cancellationToken: cancellati |
| | 0 | 351 | | await _loggingService.CompleteStepAsync(step6Id, |
| | 0 | 352 | | new { processedCount, failedCount, statusSkipped = skippedOrders.Count, warehouseSkipped = warehouseSkip |
| | 0 | 353 | | cancellationToken); |
| | 0 | 354 | | await _loggingService.CompleteExecutionAsync(executionId, cancellationToken); |
| | 0 | 355 | | await TryNotifyTransactionCompletedAsync("Возвраты покупателей", |
| | 0 | 356 | | shipmentNumbers.Count, matchedOrders.Count, processedCount, failedCount); |
| | | 357 | | |
| | 0 | 358 | | var totalSkipped = skippedOrders.Count + warehouseSkippedCount; |
| | 0 | 359 | | await SendCompleteAsync(jobId, |
| | 0 | 360 | | $"<strong>Всего:</strong> {shipmentNumbers.Count} | <strong>Найдено:</strong> {matchedOrders.Count} | " |
| | 0 | 361 | | $"<strong>Проведено:</strong> {processedCount} | <strong>Пропущено:</strong> {totalSkipped} | <strong>Ош |
| | 0 | 362 | | await SendProgressAsync(jobId, 100, "Готово"); |
| | | 363 | | |
| | 0 | 364 | | await MaybeScheduleRetryAsync( |
| | 0 | 365 | | executionId, scheduleId, "CustomerReturn", ozonClientId, daysBack, jobId, retryAttempt, cancellationToke |
| | 0 | 366 | | } |
| | 0 | 367 | | catch (Exception ex) |
| | | 368 | | { |
| | 0 | 369 | | await _loggingService.FailExecutionAsync(executionId, ex.Message, ex.StackTrace, cancellationToken); |
| | 0 | 370 | | await SendErrorAsync(jobId, ex.Message); |
| | 0 | 371 | | await MaybeScheduleRetryAsync( |
| | 0 | 372 | | executionId, scheduleId, "CustomerReturn", ozonClientId, daysBack, jobId, retryAttempt, cancellationToke |
| | 0 | 373 | | throw; |
| | 0 | 374 | | } |
| | 0 | 375 | | } |
| | | 376 | | |
| | | 377 | | private async Task ProcessShippedToCommissionerInternalAsync( |
| | | 378 | | int ozonClientId, |
| | | 379 | | int daysBack, |
| | | 380 | | int? scheduleId, |
| | | 381 | | string triggerType, |
| | | 382 | | string? jobId, |
| | | 383 | | int retryAttempt, |
| | | 384 | | CancellationToken cancellationToken = default) |
| | | 385 | | { |
| | 0 | 386 | | var executionId = await _loggingService.StartExecutionAsync(scheduleId, "ShippedToCommissioner", triggerType, ca |
| | | 387 | | |
| | | 388 | | try |
| | | 389 | | { |
| | 0 | 390 | | if (retryAttempt > 0) |
| | | 391 | | { |
| | 0 | 392 | | await SendLogAsync(jobId, $"↻ Повторная попытка {retryAttempt}/{TransactionJobRetryPolicy.MaxRetryAttemp |
| | | 393 | | } |
| | | 394 | | |
| | 0 | 395 | | await SendLogAsync(jobId, $"Старт обработки. Execution ID: {executionId}"); |
| | 0 | 396 | | Console.WriteLine($"[AutomatedTransactionProcessing] Execution {executionId} started"); |
| | | 397 | | |
| | | 398 | | // Step 1: широкая выгрузка у Ozon (ProcessedAt ~ месяц), отбор строк — вчера MSK по дате доставки |
| | 0 | 399 | | var step1Id = await _loggingService.StartStepAsync(executionId, 1, "LoadReport", new { ozonClientId, daysBac |
| | 0 | 400 | | await SendLogAsync(jobId, "Шаг 1/8: Загрузка отчёта от Ozon API..."); |
| | 0 | 401 | | var reportPeriods = BuildReportPeriods(daysBack); |
| | 0 | 402 | | await SendLogAsync(jobId, |
| | 0 | 403 | | $"Загрузка отчёта (API): {reportPeriods.DownloadFrom:dd.MM.yyyy} — {reportPeriods.DownloadTo:dd.MM.yyyy} |
| | 0 | 404 | | await SendLogAsync(jobId, |
| | 0 | 405 | | $"Отбор строк «{ReportDeliveryDateFilter.DeliveryDateColumnName}»: {reportPeriods.FilterDateKeys[0]} (вч |
| | 0 | 406 | | var oneCOperationDate = reportPeriods.TargetDay; |
| | | 407 | | |
| | 0 | 408 | | var (fileBytes, fileName, parsedOrders) = await _reportLoader.LoadAndParseReportAsync( |
| | 0 | 409 | | ozonClientId, |
| | 0 | 410 | | reportPeriods.DownloadFrom, |
| | 0 | 411 | | reportPeriods.DownloadTo, |
| | 0 | 412 | | reportPeriods.FilterDateKeys, |
| | 0 | 413 | | executionId, |
| | 0 | 414 | | step1Id, |
| | 0 | 415 | | _loggingService, |
| | 0 | 416 | | cancellationToken); |
| | | 417 | | |
| | 0 | 418 | | await _loggingService.CompleteStepAsync(step1Id, new { ordersCount = parsedOrders.Count }, cancellationToken |
| | 0 | 419 | | await _loggingService.UpdateExecutionStatsAsync(executionId, totalOrders: parsedOrders.Count, cancellationTo |
| | 0 | 420 | | await SendLogAsync(jobId, $"✓ Загружено {parsedOrders.Count} строк из файла {fileName}"); |
| | 0 | 421 | | await SendProgressAsync(jobId, 14, "Отчёт загружен и отфильтрован"); |
| | | 422 | | |
| | | 423 | | // Step 2: Match orders in database |
| | 0 | 424 | | var step2Id = await _loggingService.StartStepAsync(executionId, 2, "MatchOrders", new { ordersCount = parsed |
| | 0 | 425 | | await SendLogAsync(jobId, "Шаг 2/8: Поиск заказов в базе данных..."); |
| | 0 | 426 | | var matchedOrders = await MatchOrdersInDatabaseAsync(executionId, step2Id, parsedOrders, jobId, cancellation |
| | 0 | 427 | | await _loggingService.CompleteStepAsync(step2Id, new { matchedCount = matchedOrders.Count }, cancellationTok |
| | 0 | 428 | | await _loggingService.UpdateExecutionStatsAsync(executionId, matchedOrders: matchedOrders.Count, cancellatio |
| | 0 | 429 | | await SendLogAsync(jobId, $"✓ Найдено {matchedOrders.Count} заказов в БД"); |
| | 0 | 430 | | await SendProgressAsync(jobId, 28, "Заказы найдены"); |
| | | 431 | | |
| | | 432 | | // Step 3: Exclude already processed orders |
| | 0 | 433 | | var step3Id = await _loggingService.StartStepAsync(executionId, 3, "ExcludeProcessedOrders", new { beforeCou |
| | 0 | 434 | | await SendLogAsync(jobId, "Шаг 3/8: Исключение уже проведённых заказов..."); |
| | 0 | 435 | | var commissionerSkippedOrders = matchedOrders.Where(IsAlreadyShippedToCommissioner).ToList(); |
| | 0 | 436 | | foreach (var skippedOrder in commissionerSkippedOrders) |
| | | 437 | | { |
| | 0 | 438 | | var match = await _context.BackgroundOrderMatches |
| | 0 | 439 | | .Where(m => m.ExecutionId == executionId && m.OrderId == skippedOrder.Id) |
| | 0 | 440 | | .OrderByDescending(m => m.CreatedAt) |
| | 0 | 441 | | .FirstOrDefaultAsync(cancellationToken); |
| | | 442 | | |
| | 0 | 443 | | if (match != null) |
| | | 444 | | { |
| | 0 | 445 | | match.IsEligibleForProcessing = false; |
| | 0 | 446 | | match.RejectionReason = "Уже имеет статус 'Отгружен комиссионеру' — пропущен"; |
| | | 447 | | } |
| | | 448 | | |
| | 0 | 449 | | await _loggingService.LogTransactionResultAsync( |
| | 0 | 450 | | executionId, |
| | 0 | 451 | | step3Id, |
| | 0 | 452 | | match?.Id, |
| | 0 | 453 | | skippedOrder.Id, |
| | 0 | 454 | | skippedOrder.ShipmentWarehouse?.Name, |
| | 0 | 455 | | null, |
| | 0 | 456 | | "Skipped", |
| | 0 | 457 | | "Уже имеет статус 'Отгружен комиссионеру' — пропущен из фоновой обработки", |
| | 0 | 458 | | cancellationToken); |
| | 0 | 459 | | } |
| | | 460 | | |
| | | 461 | | // Не фильтруем по IsAccepted: после «Отгружен реализатором» заказ уже IsAccepted=true, |
| | | 462 | | // но его всё равно нужно довести до «Отгружен комиссионеру» (только смена статуса). |
| | 0 | 463 | | var unprocessedOrders = matchedOrders |
| | 0 | 464 | | .Where(o => !IsAlreadyShippedToCommissioner(o)) |
| | 0 | 465 | | .ToList(); |
| | 0 | 466 | | var excludedCount = matchedOrders.Count - unprocessedOrders.Count; |
| | 0 | 467 | | await _loggingService.CompleteStepAsync(step3Id, new { beforeCount = matchedOrders.Count, afterCount = unpro |
| | 0 | 468 | | if (commissionerSkippedOrders.Any()) |
| | | 469 | | { |
| | 0 | 470 | | await _context.SaveChangesAsync(cancellationToken); |
| | 0 | 471 | | await SendLogAsync(jobId, $"✓ Пропущено по статусу 'Отгружен комиссионеру': {commissionerSkippedOrders.C |
| | | 472 | | } |
| | 0 | 473 | | await SendLogAsync(jobId, $"✓ Исключено {excludedCount} уже проведённых заказов"); |
| | 0 | 474 | | await SendLogAsync(jobId, $"✓ Осталось {unprocessedOrders.Count} подходящих заказов"); |
| | 0 | 475 | | await SendProgressAsync(jobId, 42, "Исключение проведённых завершено"); |
| | | 476 | | |
| | | 477 | | // Step 4: Filter eligible orders |
| | 0 | 478 | | var step4Id = await _loggingService.StartStepAsync(executionId, 4, "FilterEligibleOrders", new { matchedCoun |
| | 0 | 479 | | await SendLogAsync(jobId, "Шаг 4/8: Фильтрация подходящих заказов..."); |
| | 0 | 480 | | var eligibleOrders = await FilterEligibleOrdersAsync(unprocessedOrders, executionId, jobId, cancellationToke |
| | 0 | 481 | | await _loggingService.CompleteStepAsync(step4Id, new { eligibleCount = eligibleOrders.Count }, cancellationT |
| | 0 | 482 | | await SendLogAsync(jobId, $"✓ Отфильтровано {eligibleOrders.Count} подходящих заказов"); |
| | 0 | 483 | | await SendProgressAsync(jobId, 56, "Фильтрация завершена"); |
| | | 484 | | |
| | | 485 | | // Steps 5–7: батчи по OrderProcessingBatchSize (склад → транзакции → 1С) |
| | 0 | 486 | | var orderBatches = eligibleOrders |
| | 0 | 487 | | .Chunk(OrderProcessingBatchSize) |
| | 0 | 488 | | .Select(batch => batch.ToList()) |
| | 0 | 489 | | .ToList(); |
| | 0 | 490 | | var batchCount = orderBatches.Count; |
| | | 491 | | |
| | 0 | 492 | | var step5Id = await _loggingService.StartStepAsync(executionId, 5, "GroupByWarehouse", |
| | 0 | 493 | | new { eligibleCount = eligibleOrders.Count, batchSize = OrderProcessingBatchSize, batchCount }, cancella |
| | 0 | 494 | | var step6Id = await _loggingService.StartStepAsync(executionId, 6, "CreateTransactions", |
| | 0 | 495 | | new { batchCount }, cancellationToken); |
| | 0 | 496 | | var step7Id = await _loggingService.StartStepAsync(executionId, 7, "PostTo1C", |
| | 0 | 497 | | new { batchCount }, cancellationToken); |
| | | 498 | | |
| | 0 | 499 | | await SendLogAsync(jobId, |
| | 0 | 500 | | $"Шаги 5–7/8: обработка {eligibleOrders.Count} заказов в {batchCount} батч(ах) по {OrderProcessingBatchS |
| | | 501 | | |
| | 0 | 502 | | var senderWarehouseByOrderId = new Dictionary<int, string>(); |
| | 0 | 503 | | var transactionResultIds = new List<long>(); |
| | 0 | 504 | | var allWarehouseFailureDetails = new List<string>(); |
| | 0 | 505 | | var totalWarehouseSkipped = 0; |
| | 0 | 506 | | var warehouseGroupCount = 0; |
| | 0 | 507 | | var successCount = 0; |
| | 0 | 508 | | var failCount = 0; |
| | | 509 | | |
| | 0 | 510 | | for (var batchIndex = 0; batchIndex < batchCount; batchIndex++) |
| | | 511 | | { |
| | 0 | 512 | | var batchOrders = orderBatches[batchIndex]; |
| | 0 | 513 | | var batchNo = batchIndex + 1; |
| | 0 | 514 | | await SendLogAsync(jobId, $"—— Батч {batchNo}/{batchCount}: {batchOrders.Count} заказов ——"); |
| | | 515 | | |
| | 0 | 516 | | var batchResolution = await ResolveCommissionerSenderWarehousesAsync( |
| | 0 | 517 | | batchOrders, executionId, step5Id, jobId, cancellationToken); |
| | 0 | 518 | | allWarehouseFailureDetails.AddRange(batchResolution.FailureDetails); |
| | 0 | 519 | | totalWarehouseSkipped += batchResolution.SkippedCount; |
| | | 520 | | |
| | 0 | 521 | | if (!batchResolution.ReadyOrders.Any()) |
| | | 522 | | { |
| | 0 | 523 | | await SendLogAsync(jobId, |
| | 0 | 524 | | $"Батч {batchNo}: ни у одного заказа не определён склад отправителя, проведение пропущено"); |
| | 0 | 525 | | continue; |
| | | 526 | | } |
| | | 527 | | |
| | 0 | 528 | | foreach (var kv in batchResolution.WarehouseByOrderId) |
| | | 529 | | { |
| | 0 | 530 | | senderWarehouseByOrderId[kv.Key] = kv.Value; |
| | | 531 | | } |
| | | 532 | | |
| | 0 | 533 | | var warehouseGroups = GroupByWarehouse( |
| | 0 | 534 | | batchResolution.ReadyOrders, batchResolution.WarehouseByOrderId); |
| | 0 | 535 | | warehouseGroupCount += warehouseGroups.Count; |
| | | 536 | | |
| | 0 | 537 | | await SendLogAsync(jobId, $"Батч {batchNo}: создание транзакций ({warehouseGroups.Count} склад(ов))…"); |
| | 0 | 538 | | var batchTransactionIds = await CreateTransactionsAsync( |
| | 0 | 539 | | executionId, step6Id, warehouseGroups, scheduleId, jobId, cancellationToken); |
| | 0 | 540 | | transactionResultIds.AddRange(batchTransactionIds); |
| | | 541 | | |
| | 0 | 542 | | if (batchTransactionIds.Any()) |
| | | 543 | | { |
| | 0 | 544 | | await SendLogAsync(jobId, $"Батч {batchNo}: проведение в 1С ({batchTransactionIds.Count} результатов |
| | 0 | 545 | | var (batchSuccess, batchFail) = await PostTransactionsTo1CAsync( |
| | 0 | 546 | | executionId, |
| | 0 | 547 | | step7Id, |
| | 0 | 548 | | batchTransactionIds, |
| | 0 | 549 | | batchResolution.WarehouseByOrderId, |
| | 0 | 550 | | oneCOperationDate, |
| | 0 | 551 | | jobId, |
| | 0 | 552 | | cancellationToken); |
| | 0 | 553 | | successCount += batchSuccess; |
| | 0 | 554 | | failCount += batchFail; |
| | | 555 | | } |
| | | 556 | | |
| | 0 | 557 | | var batchProgress = 70 + (int)Math.Round(28.0 * batchNo / batchCount); |
| | 0 | 558 | | await SendProgressAsync(jobId, batchProgress, $"Батч {batchNo}/{batchCount} обработан"); |
| | 0 | 559 | | } |
| | | 560 | | |
| | 0 | 561 | | if (!transactionResultIds.Any() && eligibleOrders.Count > 0) |
| | | 562 | | { |
| | 0 | 563 | | var fullError = BuildWarehouseResolutionFailureMessage( |
| | 0 | 564 | | allWarehouseFailureDetails, eligibleOrders.Count, totalWarehouseSkipped); |
| | 0 | 565 | | await _loggingService.FailStepAsync(step5Id, TruncateErrorMessage(fullError), cancellationToken); |
| | 0 | 566 | | await _loggingService.FailExecutionAsync(executionId, TruncateErrorMessage(fullError), null, cancellatio |
| | 0 | 567 | | await SendErrorAsync(jobId, TruncateErrorMessage(fullError)); |
| | 0 | 568 | | return; |
| | | 569 | | } |
| | | 570 | | |
| | 0 | 571 | | await _loggingService.CompleteStepAsync(step5Id, |
| | 0 | 572 | | new { warehouseCount = warehouseGroupCount, batchCount, warehouseSkipped = totalWarehouseSkipped }, |
| | 0 | 573 | | cancellationToken); |
| | 0 | 574 | | await SendLogAsync(jobId, |
| | 0 | 575 | | $"✓ Склады: {warehouseGroupCount} групп, пропущено без связки: {totalWarehouseSkipped}"); |
| | 0 | 576 | | await SendProgressAsync(jobId, 70, "Группировка завершена"); |
| | | 577 | | |
| | 0 | 578 | | await _loggingService.CompleteStepAsync(step6Id, new { createdCount = transactionResultIds.Count }, cancella |
| | 0 | 579 | | await _loggingService.UpdateExecutionStatsAsync(executionId, processedOrders: transactionResultIds.Count, ca |
| | 0 | 580 | | await SendLogAsync(jobId, $"✓ Создано результатов транзакций: {transactionResultIds.Count}"); |
| | 0 | 581 | | await SendProgressAsync(jobId, 84, "Транзакции созданы"); |
| | | 582 | | |
| | 0 | 583 | | await _loggingService.CompleteStepAsync(step7Id, new { successCount, failCount }, cancellationToken); |
| | 0 | 584 | | await _loggingService.UpdateExecutionStatsAsync(executionId, successfulOrders: successCount, failedOrders: f |
| | 0 | 585 | | await SendLogAsync(jobId, $"✓ Проведено в 1С: {successCount} успешно, {failCount} ошибок"); |
| | 0 | 586 | | await SendProgressAsync(jobId, 98, "1С проведение завершено"); |
| | | 587 | | |
| | | 588 | | // Step 8: Finalize |
| | 0 | 589 | | await SendLogAsync(jobId, "Шаг 8/8: Финализация..."); |
| | 0 | 590 | | await _loggingService.CompleteExecutionAsync(executionId, cancellationToken); |
| | 0 | 591 | | await TryNotifyTransactionCompletedAsync("Отгружен комиссионеру", |
| | 0 | 592 | | parsedOrders.Count, matchedOrders.Count, successCount, failCount); |
| | 0 | 593 | | await SendLogAsync(jobId, "✓ Обработка завершена"); |
| | 0 | 594 | | await SendProgressAsync(jobId, 100, "Готово"); |
| | 0 | 595 | | await SendCompleteAsync(jobId, $"<strong>Всего:</strong> {parsedOrders.Count} | <strong>Найдено:</strong> {m |
| | 0 | 596 | | Console.WriteLine($"[AutomatedTransactionProcessing] Execution {executionId} completed successfully"); |
| | | 597 | | |
| | 0 | 598 | | await MaybeScheduleRetryAsync( |
| | 0 | 599 | | executionId, scheduleId, "ShippedToCommissioner", ozonClientId, daysBack, jobId, retryAttempt, cancellat |
| | 0 | 600 | | } |
| | 0 | 601 | | catch (Exception ex) |
| | | 602 | | { |
| | 0 | 603 | | Console.WriteLine($"[AutomatedTransactionProcessing] Execution {executionId} failed: {ex.Message}"); |
| | 0 | 604 | | await _loggingService.FailExecutionAsync(executionId, ex.Message, ex.StackTrace, cancellationToken); |
| | 0 | 605 | | await SendErrorAsync(jobId, ex.Message); |
| | 0 | 606 | | await MaybeScheduleRetryAsync( |
| | 0 | 607 | | executionId, scheduleId, "ShippedToCommissioner", ozonClientId, daysBack, jobId, retryAttempt, cancellat |
| | 0 | 608 | | throw; |
| | 0 | 609 | | } |
| | 0 | 610 | | } |
| | | 611 | | |
| | | 612 | | private static async Task TryNotifyTransactionCompletedAsync( |
| | | 613 | | string jobType, int total, int matched, int success, int failed) |
| | | 614 | | { |
| | | 615 | | try |
| | | 616 | | { |
| | 0 | 617 | | var color = failed > 0 ? "#D97706" : "#16A34A"; |
| | 0 | 618 | | var icon = failed > 0 ? "fa-triangle-exclamation" : "fa-check"; |
| | 0 | 619 | | await NotificationService.NotifyAsync( |
| | 0 | 620 | | "Транзакции", color, |
| | 0 | 621 | | $"{jobType}: всего {total}, найдено {matched}, проведено {success}, ошибок {failed}", |
| | 0 | 622 | | icon); |
| | 0 | 623 | | } |
| | 0 | 624 | | catch { /* не роняем джоб */ } |
| | 0 | 625 | | } |
| | | 626 | | |
| | | 627 | | private async Task MaybeScheduleRetryAsync( |
| | | 628 | | long executionId, |
| | | 629 | | int? scheduleId, |
| | | 630 | | string jobType, |
| | | 631 | | int ozonClientId, |
| | | 632 | | int daysBack, |
| | | 633 | | string? jobId, |
| | | 634 | | int retryAttempt, |
| | | 635 | | CancellationToken cancellationToken) |
| | | 636 | | { |
| | 0 | 637 | | if (retryAttempt >= TransactionJobRetryPolicy.MaxRetryAttempts) |
| | | 638 | | { |
| | 0 | 639 | | var limitMessage = |
| | 0 | 640 | | $"⚠ Лимит повторных запусков исчерпан ({TransactionJobRetryPolicy.MaxRetryAttempts})"; |
| | 0 | 641 | | Console.WriteLine($"[TransactionJobRetry] {limitMessage} execution={executionId}"); |
| | 0 | 642 | | await SendLogAsync(jobId, limitMessage); |
| | 0 | 643 | | return; |
| | | 644 | | } |
| | | 645 | | |
| | 0 | 646 | | var execution = await _loggingService.GetExecutionAsync(executionId, cancellationToken); |
| | 0 | 647 | | var hasFailedTransactionResults = await _context.BackgroundTransactionResults |
| | 0 | 648 | | .AnyAsync( |
| | 0 | 649 | | r => r.ExecutionId == executionId && r.Status == "Failed", |
| | 0 | 650 | | cancellationToken); |
| | | 651 | | |
| | 0 | 652 | | if (!TransactionJobRetryPolicy.ShouldRetry(execution, hasFailedTransactionResults)) |
| | 0 | 653 | | return; |
| | | 654 | | |
| | 0 | 655 | | var nextAttempt = retryAttempt + 1; |
| | 0 | 656 | | var delay = TransactionJobRetryPolicy.GetDelayForAttempt(nextAttempt); |
| | 0 | 657 | | var delayText = delay.TotalMinutes >= 60 |
| | 0 | 658 | | ? $"{delay.TotalHours:0.#} ч" |
| | 0 | 659 | | : $"{delay.TotalMinutes:0} мин"; |
| | 0 | 660 | | var logMessage = |
| | 0 | 661 | | $"↻ Запланирован повтор {nextAttempt}/{TransactionJobRetryPolicy.MaxRetryAttempts} через {delayText} " + |
| | 0 | 662 | | $"(статус: {execution?.Status}, ошибок заказов: {execution?.FailedOrders ?? 0})"; |
| | | 663 | | |
| | 0 | 664 | | Console.WriteLine($"[TransactionJobRetry] {logMessage} execution={executionId}"); |
| | 0 | 665 | | await SendLogAsync(jobId, logMessage); |
| | | 666 | | |
| | 0 | 667 | | if (scheduleId.HasValue) |
| | | 668 | | { |
| | 0 | 669 | | var schedule = await _scheduleService.GetScheduleByIdAsync(scheduleId.Value, cancellationToken); |
| | 0 | 670 | | if (schedule is { IsActive: true }) |
| | 0 | 671 | | _retryScheduler.ScheduleScheduledRetry(scheduleId.Value, jobType, nextAttempt); |
| | | 672 | | } |
| | | 673 | | else |
| | | 674 | | { |
| | 0 | 675 | | _retryScheduler.ScheduleManualRetry(ozonClientId, daysBack, jobType, jobId, nextAttempt); |
| | | 676 | | } |
| | 0 | 677 | | } |
| | | 678 | | |
| | | 679 | | private async Task SendLogAsync(string? jobId, string message) |
| | | 680 | | { |
| | 0 | 681 | | if (string.IsNullOrWhiteSpace(jobId)) return; |
| | 0 | 682 | | await _hubContext.Clients.Group(jobId).SendAsync("Log", message); |
| | 0 | 683 | | } |
| | | 684 | | |
| | | 685 | | private async Task SendProgressAsync(string? jobId, int percent, string message) |
| | | 686 | | { |
| | 0 | 687 | | if (string.IsNullOrWhiteSpace(jobId)) return; |
| | 0 | 688 | | await _hubContext.Clients.Group(jobId).SendAsync("Progress", percent, message); |
| | 0 | 689 | | } |
| | | 690 | | |
| | | 691 | | private async Task SendCompleteAsync(string? jobId, string summary) |
| | | 692 | | { |
| | 0 | 693 | | if (string.IsNullOrWhiteSpace(jobId)) return; |
| | 0 | 694 | | await _hubContext.Clients.Group(jobId).SendAsync("Complete", summary); |
| | 0 | 695 | | } |
| | | 696 | | |
| | | 697 | | private async Task SendErrorAsync(string? jobId, string errorMessage) |
| | | 698 | | { |
| | 0 | 699 | | if (string.IsNullOrWhiteSpace(jobId)) return; |
| | 0 | 700 | | await _hubContext.Clients.Group(jobId).SendAsync("Error", errorMessage); |
| | 0 | 701 | | } |
| | | 702 | | |
| | | 703 | | private static ReportDeliveryDateFilter.TransactionJobReportPeriods BuildReportPeriods(int daysBack) => |
| | 0 | 704 | | ReportDeliveryDateFilter.BuildTransactionJobPeriods( |
| | 0 | 705 | | DateTime.UtcNow, |
| | 0 | 706 | | RussianTimeZone, |
| | 0 | 707 | | daysBack < 1 ? ReportDeliveryDateFilter.TransactionJobDaysBack : daysBack); |
| | | 708 | | |
| | | 709 | | private async Task<List<Order>> MatchOrdersInDatabaseAsync(long executionId, long stepId, List<(string OrderNumber, |
| | | 710 | | { |
| | 0 | 711 | | var batches = parsedOrders.Chunk(OrderProcessingBatchSize).Select(c => c.ToList()).ToList(); |
| | 0 | 712 | | await SendLogAsync(jobId, |
| | 0 | 713 | | $"Поиск {parsedOrders.Count} заказов в базе данных ({batches.Count} батч(ей) по {OrderProcessingBatchSize})… |
| | | 714 | | |
| | 0 | 715 | | var ordersById = new Dictionary<int, Order>(); |
| | 0 | 716 | | var orderMatches = new List<BackgroundOrderMatch>(); |
| | | 717 | | |
| | 0 | 718 | | for (var batchIndex = 0; batchIndex < batches.Count; batchIndex++) |
| | | 719 | | { |
| | 0 | 720 | | var batch = batches[batchIndex]; |
| | 0 | 721 | | if (batches.Count > 1) |
| | | 722 | | { |
| | 0 | 723 | | await SendLogAsync(jobId, $"Поиск в БД: батч {batchIndex + 1}/{batches.Count} ({batch.Count} строк)…"); |
| | | 724 | | } |
| | | 725 | | |
| | 0 | 726 | | var orderIds = await _orderServices.GetOrderIdsByNumbersAndArticles(batch); |
| | 0 | 727 | | var batchOrders = await _orderServices.GetOrdersNoTracking(orderIds.ToArray()); |
| | | 728 | | |
| | 0 | 729 | | foreach (var parsed in batch) |
| | | 730 | | { |
| | | 731 | | // Только заказы, реально сопоставленные строке отчёта: поиск по номеру+артикулу |
| | | 732 | | // может вернуть и соседние отправления того же заказа, которых в отчёте нет. |
| | 0 | 733 | | var matchedForRow = FindOrdersForReportRow(batchOrders, parsed); |
| | | 734 | | |
| | 0 | 735 | | if (matchedForRow.Count == 0) |
| | | 736 | | { |
| | 0 | 737 | | orderMatches.Add(new BackgroundOrderMatch |
| | 0 | 738 | | { |
| | 0 | 739 | | ExecutionId = executionId, |
| | 0 | 740 | | StepId = stepId, |
| | 0 | 741 | | OrderNumber = parsed.OrderNumber, |
| | 0 | 742 | | Article = parsed.Article, |
| | 0 | 743 | | OrderId = null, |
| | 0 | 744 | | OrderStatus = null, |
| | 0 | 745 | | IsMatchedInDb = false, |
| | 0 | 746 | | IsEligibleForProcessing = false, |
| | 0 | 747 | | RejectionReason = "Заказ не найден в БД", |
| | 0 | 748 | | CreatedAt = DateTime.UtcNow |
| | 0 | 749 | | }); |
| | 0 | 750 | | continue; |
| | | 751 | | } |
| | | 752 | | |
| | 0 | 753 | | foreach (var order in matchedForRow) |
| | | 754 | | { |
| | 0 | 755 | | ordersById[order.Id] = order; |
| | 0 | 756 | | orderMatches.Add(new BackgroundOrderMatch |
| | 0 | 757 | | { |
| | 0 | 758 | | ExecutionId = executionId, |
| | 0 | 759 | | StepId = stepId, |
| | 0 | 760 | | OrderNumber = parsed.OrderNumber, |
| | 0 | 761 | | Article = parsed.Article, |
| | 0 | 762 | | OrderId = order.Id, |
| | 0 | 763 | | OrderStatus = order.AppStatus?.Name ?? order.Status, |
| | 0 | 764 | | IsMatchedInDb = true, |
| | 0 | 765 | | IsEligibleForProcessing = false, |
| | 0 | 766 | | RejectionReason = null, |
| | 0 | 767 | | CreatedAt = DateTime.UtcNow |
| | 0 | 768 | | }); |
| | | 769 | | } |
| | | 770 | | } |
| | 0 | 771 | | } |
| | | 772 | | |
| | 0 | 773 | | await SendLogAsync(jobId, $"База данных вернула {ordersById.Count} совпадений"); |
| | 0 | 774 | | await _loggingService.BulkLogOrderMatchesAsync(orderMatches, cancellationToken); |
| | 0 | 775 | | return ordersById.Values.ToList(); |
| | 0 | 776 | | } |
| | | 777 | | |
| | | 778 | | /// <summary> |
| | | 779 | | /// Заказы, соответствующие строке отчёта: совпадение по номеру отправления (без внутреннего |
| | | 780 | | /// суффикса позиции «/1») и артикулу. Разделённый заказ даёт разные отправления («-1», «-3»), |
| | | 781 | | /// и подтягивать соседнее отправление по строке отчёта нельзя. |
| | | 782 | | /// </summary> |
| | | 783 | | internal static List<Order> FindOrdersForReportRow( |
| | | 784 | | IEnumerable<Order?> candidates, |
| | | 785 | | (string OrderNumber, string Article) reportRow) |
| | | 786 | | { |
| | 6 | 787 | | var normalizedNumber = ShipmentNumberMatching.Normalize(reportRow.OrderNumber); |
| | 6 | 788 | | if (string.IsNullOrEmpty(normalizedNumber)) |
| | 1 | 789 | | return []; |
| | | 790 | | |
| | 5 | 791 | | return candidates |
| | 5 | 792 | | .Where(o => |
| | 9 | 793 | | o != null && |
| | 9 | 794 | | string.Equals( |
| | 9 | 795 | | ShipmentNumberMatching.Normalize(o.ShipmentNumber), |
| | 9 | 796 | | normalizedNumber, |
| | 9 | 797 | | StringComparison.OrdinalIgnoreCase) && |
| | 9 | 798 | | string.Equals(o.ProductKey, reportRow.Article, StringComparison.OrdinalIgnoreCase)) |
| | 5 | 799 | | .Select(o => o!) |
| | 5 | 800 | | .ToList(); |
| | | 801 | | } |
| | | 802 | | |
| | | 803 | | private async Task<List<Order>> FilterEligibleOrdersAsync( |
| | | 804 | | List<Order> orders, long executionId, string? jobId, CancellationToken cancellationToken) |
| | | 805 | | { |
| | 0 | 806 | | var eligibleOrders = orders.Where(IsEligibleForAutomatedProcessing).ToList(); |
| | | 807 | | |
| | 0 | 808 | | var orderIds = orders.Select(o => o.Id).ToList(); |
| | 0 | 809 | | var allMatches = await _context.BackgroundOrderMatches |
| | 0 | 810 | | .Where(m => m.ExecutionId == executionId && m.OrderId != null && orderIds.Contains(m.OrderId.Value)) |
| | 0 | 811 | | .OrderByDescending(m => m.CreatedAt) |
| | 0 | 812 | | .ToListAsync(cancellationToken); |
| | 0 | 813 | | var latestMatchByOrderId = allMatches |
| | 0 | 814 | | .GroupBy(m => m.OrderId!.Value) |
| | 0 | 815 | | .ToDictionary(g => g.Key, g => g.First()); |
| | | 816 | | |
| | 0 | 817 | | foreach (var order in orders) |
| | | 818 | | { |
| | 0 | 819 | | var isEligible = eligibleOrders.Contains(order); |
| | 0 | 820 | | if (!latestMatchByOrderId.TryGetValue(order.Id, out var match)) continue; |
| | 0 | 821 | | match.IsEligibleForProcessing = isEligible; |
| | 0 | 822 | | match.RejectionReason = isEligible ? null : $"Статус '{order.AppStatus?.Name}' не подходит для обработки"; |
| | | 823 | | } |
| | | 824 | | |
| | 0 | 825 | | await _context.SaveChangesAsync(cancellationToken); |
| | 0 | 826 | | return eligibleOrders; |
| | 0 | 827 | | } |
| | | 828 | | |
| | | 829 | | private async Task<CommissionerWarehouseBatchResult> ResolveCommissionerSenderWarehousesAsync( |
| | | 830 | | List<Order> eligibleOrders, |
| | | 831 | | long executionId, |
| | | 832 | | long stepId, |
| | | 833 | | string? jobId, |
| | | 834 | | CancellationToken cancellationToken) |
| | | 835 | | { |
| | 0 | 836 | | var resolution = await _warehouseSelectionResolver.ResolveCommissionerSenderWarehousesAsync(eligibleOrders); |
| | 0 | 837 | | var readyOrders = new List<Order>(); |
| | 0 | 838 | | var warehouseByOrderId = new Dictionary<int, string>(); |
| | 0 | 839 | | var failureDetails = new List<string>(); |
| | 0 | 840 | | var skippedCount = 0; |
| | | 841 | | |
| | | 842 | | // Batch-load matches once instead of one query per skipped order |
| | 0 | 843 | | var orderIds = eligibleOrders.Select(o => o.Id).ToList(); |
| | 0 | 844 | | var allMatches = await _context.BackgroundOrderMatches |
| | 0 | 845 | | .Where(m => m.ExecutionId == executionId && m.OrderId != null && orderIds.Contains(m.OrderId.Value)) |
| | 0 | 846 | | .OrderByDescending(m => m.CreatedAt) |
| | 0 | 847 | | .ToListAsync(cancellationToken); |
| | 0 | 848 | | var matchByOrderId = allMatches |
| | 0 | 849 | | .GroupBy(m => m.OrderId!.Value) |
| | 0 | 850 | | .ToDictionary(g => g.Key, g => g.First()); |
| | | 851 | | |
| | 0 | 852 | | foreach (var order in eligibleOrders) |
| | | 853 | | { |
| | 0 | 854 | | if (resolution.WarehouseByOrderId.TryGetValue(order.Id, out var warehouse) && |
| | 0 | 855 | | !string.IsNullOrWhiteSpace(warehouse)) |
| | | 856 | | { |
| | 0 | 857 | | warehouseByOrderId[order.Id] = warehouse.Trim(); |
| | 0 | 858 | | readyOrders.Add(order); |
| | 0 | 859 | | continue; |
| | | 860 | | } |
| | | 861 | | |
| | 0 | 862 | | skippedCount++; |
| | 0 | 863 | | var reason = resolution.BlockingErrors |
| | 0 | 864 | | .FirstOrDefault(e => (order.ShipmentNumber != null && |
| | 0 | 865 | | e.Contains(order.ShipmentNumber, StringComparison.OrdinalIgnoreCase)) || |
| | 0 | 866 | | e.Contains(order.Id.ToString(), StringComparison.OrdinalIgnoreCase)) |
| | 0 | 867 | | ?? "Не найдена связка WarehouseMapping для склада отправителя"; |
| | 0 | 868 | | var detail = $"{order.ShipmentNumber ?? $"ID {order.Id}"}: {reason}"; |
| | 0 | 869 | | failureDetails.Add(detail); |
| | 0 | 870 | | await SendLogAsync(jobId, $"⊘ {detail}"); |
| | 0 | 871 | | matchByOrderId.TryGetValue(order.Id, out var match); |
| | 0 | 872 | | await LogCommissionerProcessingSkippedAsync( |
| | 0 | 873 | | executionId, stepId, order, null, reason, match, cancellationToken); |
| | 0 | 874 | | } |
| | | 875 | | |
| | 0 | 876 | | if (skippedCount > 0) |
| | | 877 | | { |
| | 0 | 878 | | await SendLogAsync(jobId, $"Пропущено заказов без склада отправителя в батче: {skippedCount}"); |
| | 0 | 879 | | await _context.SaveChangesAsync(cancellationToken); // batch save after all skips |
| | | 880 | | } |
| | | 881 | | |
| | 0 | 882 | | if (readyOrders.Any()) |
| | | 883 | | { |
| | 0 | 884 | | foreach (var group in warehouseByOrderId |
| | 0 | 885 | | .GroupBy(kv => kv.Value, StringComparer.OrdinalIgnoreCase) |
| | 0 | 886 | | .OrderBy(g => g.Key)) |
| | | 887 | | { |
| | 0 | 888 | | await SendLogAsync(jobId, |
| | 0 | 889 | | $"Склад отправителя (связка): {group.Key} — заказов {group.Count()}"); |
| | | 890 | | } |
| | | 891 | | } |
| | | 892 | | |
| | 0 | 893 | | return new CommissionerWarehouseBatchResult |
| | 0 | 894 | | { |
| | 0 | 895 | | ReadyOrders = readyOrders, |
| | 0 | 896 | | WarehouseByOrderId = warehouseByOrderId, |
| | 0 | 897 | | SkippedCount = skippedCount, |
| | 0 | 898 | | FailureDetails = failureDetails |
| | 0 | 899 | | }; |
| | 0 | 900 | | } |
| | | 901 | | |
| | | 902 | | internal static string BuildWarehouseResolutionFailureMessage( |
| | | 903 | | IReadOnlyList<string> details, |
| | | 904 | | int eligibleCount, |
| | | 905 | | int skippedCount) |
| | | 906 | | { |
| | 4 | 907 | | var header = |
| | 4 | 908 | | $"Не удалось определить склад отправителя по связкам складов (WarehouseMapping). " + |
| | 4 | 909 | | $"Подходящих заказов: {eligibleCount}, без связки: {skippedCount}."; |
| | | 910 | | |
| | 4 | 911 | | if (details.Count == 0) |
| | | 912 | | { |
| | 1 | 913 | | return header + " Детали по заказам не собраны — проверьте логи этапа «Группировка по складам»."; |
| | | 914 | | } |
| | | 915 | | |
| | 3 | 916 | | var distinct = details.Distinct(StringComparer.OrdinalIgnoreCase).Take(150).ToList(); |
| | 3 | 917 | | var body = string.Join(Environment.NewLine, distinct); |
| | 3 | 918 | | if (details.Count > distinct.Count) |
| | | 919 | | { |
| | 2 | 920 | | body += Environment.NewLine + $"... и ещё {details.Count - distinct.Count} записей (см. лог задания)."; |
| | | 921 | | } |
| | | 922 | | |
| | 3 | 923 | | return header + Environment.NewLine + body; |
| | | 924 | | } |
| | | 925 | | |
| | | 926 | | internal static string TruncateErrorMessage(string message) |
| | | 927 | | { |
| | 5 | 928 | | if (string.IsNullOrEmpty(message) || message.Length <= MaxExecutionErrorMessageLength) |
| | | 929 | | { |
| | 4 | 930 | | return message; |
| | | 931 | | } |
| | | 932 | | |
| | 1 | 933 | | return message[..MaxExecutionErrorMessageLength] + "…"; |
| | | 934 | | } |
| | | 935 | | |
| | | 936 | | internal static Dictionary<string, List<Order>> GroupByWarehouse( |
| | | 937 | | List<Order> orders, |
| | | 938 | | IReadOnlyDictionary<int, string> senderWarehouseByOrderId) |
| | | 939 | | { |
| | 7 | 940 | | return orders |
| | 11 | 941 | | .GroupBy(o => senderWarehouseByOrderId.TryGetValue(o.Id, out var wh) && !string.IsNullOrWhiteSpace(wh) |
| | 11 | 942 | | ? wh |
| | 11 | 943 | | : "Склад не определен", |
| | 7 | 944 | | StringComparer.OrdinalIgnoreCase) |
| | 21 | 945 | | .ToDictionary(g => g.Key, g => g.ToList()); |
| | | 946 | | } |
| | | 947 | | |
| | | 948 | | internal static string BuildAutomatedCommissionerComment(int? scheduleId) => |
| | 3 | 949 | | $"Проведено автоматически системой {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC" + |
| | 3 | 950 | | (scheduleId.HasValue ? $" (расписание ID: {scheduleId.Value})" : " (ручной запуск)"); |
| | | 951 | | |
| | | 952 | | private async Task<List<long>> CreateTransactionsAsync( |
| | | 953 | | long executionId, long stepId, Dictionary<string, List<Order>> warehouseGroups, int? scheduleId, string? jobId, |
| | | 954 | | { |
| | 0 | 955 | | var resultIds = new List<long>(); |
| | 0 | 956 | | var successfulTransactions = new List<(int transactionId, int orderId, string warehouseName)>(); |
| | 0 | 957 | | var failedTransactions = new List<(int orderId, string warehouseName, string errorMessage)>(); |
| | 0 | 958 | | var commissionerStatus = await _appStatusServices.GetAppStatusAsync(new AppStatus { Name = CommissionerStatusNam |
| | 0 | 959 | | if (commissionerStatus == null) |
| | | 960 | | { |
| | 0 | 961 | | throw new InvalidOperationException($"Не найден статус '{CommissionerStatusName}'"); |
| | | 962 | | } |
| | | 963 | | |
| | 0 | 964 | | foreach (var (warehouseName, orders) in warehouseGroups) |
| | | 965 | | { |
| | 0 | 966 | | if (warehouseName == "Склад не определен") |
| | | 967 | | { |
| | 0 | 968 | | await SendLogAsync(jobId, $"Пропущен склад '{warehouseName}' с {orders.Count} заказами"); |
| | 0 | 969 | | continue; |
| | | 970 | | } |
| | | 971 | | |
| | 0 | 972 | | var statusOnlyOrders = orders.Where(IsStatusOnlyCommissionerChange).ToList(); |
| | 0 | 973 | | var transactionOrders = orders.Where(o => !IsStatusOnlyCommissionerChange(o)).ToList(); |
| | | 974 | | |
| | 0 | 975 | | if (statusOnlyOrders.Any()) |
| | | 976 | | { |
| | 0 | 977 | | resultIds.AddRange(await ApplyCommissionerStatusOnlyAsync( |
| | 0 | 978 | | executionId, |
| | 0 | 979 | | stepId, |
| | 0 | 980 | | statusOnlyOrders, |
| | 0 | 981 | | warehouseName, |
| | 0 | 982 | | scheduleId, |
| | 0 | 983 | | commissionerStatus, |
| | 0 | 984 | | jobId, |
| | 0 | 985 | | cancellationToken)); |
| | | 986 | | } |
| | | 987 | | |
| | 0 | 988 | | if (!transactionOrders.Any()) |
| | | 989 | | { |
| | | 990 | | continue; |
| | | 991 | | } |
| | | 992 | | |
| | 0 | 993 | | await SendLogAsync(jobId, |
| | 0 | 994 | | $"Создание транзакции для склада '{warehouseName}' ({transactionOrders.Count} заказов, с документом и 1С |
| | | 995 | | |
| | | 996 | | try |
| | | 997 | | { |
| | 0 | 998 | | var comment = BuildAutomatedCommissionerComment(scheduleId); |
| | 0 | 999 | | var performedAt = DateTime.UtcNow; |
| | 0 | 1000 | | var fromStatusByOrderId = transactionOrders.ToDictionary(o => o.Id, o => o.AppStatusId ?? 0); |
| | 0 | 1001 | | ApplySystemAttribution(transactionOrders); |
| | 0 | 1002 | | ClearOrderNavigationForPersist(transactionOrders); |
| | | 1003 | | |
| | 0 | 1004 | | foreach (var order in transactionOrders) |
| | | 1005 | | { |
| | 0 | 1006 | | if (!string.Equals(order.Status, "Отменен", StringComparison.OrdinalIgnoreCase)) |
| | | 1007 | | { |
| | 0 | 1008 | | order.AppStatusId = commissionerStatus.Id; |
| | 0 | 1009 | | order.AppStatus = commissionerStatus; |
| | | 1010 | | } |
| | | 1011 | | } |
| | | 1012 | | |
| | 0 | 1013 | | var (_, _, transactionId) = await _transactionManager.CreateShippedToCommissionerTransaction( |
| | 0 | 1014 | | transactionOrders, |
| | 0 | 1015 | | SystemUserName, |
| | 0 | 1016 | | performedAt, |
| | 0 | 1017 | | comment); |
| | | 1018 | | |
| | 0 | 1019 | | foreach (var order in transactionOrders) |
| | | 1020 | | { |
| | 0 | 1021 | | order.AppStatus = null; |
| | | 1022 | | } |
| | | 1023 | | |
| | 0 | 1024 | | await _orderServices.UpdateOrders(transactionOrders); |
| | 0 | 1025 | | await TryRecordStatusTransitionHistoryAsync( |
| | 0 | 1026 | | TransactionType.ShippedToCommissioner, |
| | 0 | 1027 | | transactionOrders, |
| | 0 | 1028 | | fromStatusByOrderId, |
| | 0 | 1029 | | comment, |
| | 0 | 1030 | | performedAt, |
| | 0 | 1031 | | cancellationToken); |
| | | 1032 | | |
| | 0 | 1033 | | foreach (var order in transactionOrders) |
| | | 1034 | | { |
| | 0 | 1035 | | successfulTransactions.Add((transactionId, order.Id, warehouseName)); |
| | | 1036 | | } |
| | | 1037 | | |
| | 0 | 1038 | | await SendLogAsync(jobId, |
| | 0 | 1039 | | $"✓ Склад '{warehouseName}': создана 1 транзакция для {transactionOrders.Count} заказов"); |
| | 0 | 1040 | | } |
| | 0 | 1041 | | catch (Exception ex) |
| | | 1042 | | { |
| | 0 | 1043 | | var errorMessage = ex.Message; |
| | 0 | 1044 | | var innerException = ex.InnerException; |
| | 0 | 1045 | | while (innerException != null) |
| | | 1046 | | { |
| | 0 | 1047 | | errorMessage += $" → {innerException.Message}"; |
| | 0 | 1048 | | innerException = innerException.InnerException; |
| | | 1049 | | } |
| | | 1050 | | |
| | 0 | 1051 | | await SendLogAsync(jobId, $"✗ Ошибка создания транзакции для склада '{warehouseName}': {errorMessage}"); |
| | 0 | 1052 | | Console.WriteLine($"[AutomatedTransactionProcessing] Transaction creation error for warehouse {warehouse |
| | | 1053 | | |
| | 0 | 1054 | | foreach (var order in transactionOrders) |
| | | 1055 | | { |
| | 0 | 1056 | | failedTransactions.Add((order.Id, warehouseName, errorMessage)); |
| | | 1057 | | } |
| | 0 | 1058 | | } |
| | 0 | 1059 | | } |
| | | 1060 | | |
| | 0 | 1061 | | foreach (var (transactionId, orderId, warehouseName) in successfulTransactions) |
| | | 1062 | | { |
| | | 1063 | | try |
| | | 1064 | | { |
| | 0 | 1065 | | var resultId = await _loggingService.LogTransactionResultAsync( |
| | 0 | 1066 | | executionId, stepId, null, orderId, warehouseName, |
| | 0 | 1067 | | transactionId, "Created", null, cancellationToken); |
| | 0 | 1068 | | resultIds.Add(resultId); |
| | 0 | 1069 | | } |
| | 0 | 1070 | | catch (Exception ex) |
| | | 1071 | | { |
| | 0 | 1072 | | await SendLogAsync(jobId, $"✗ Ошибка логирования результата для заказа {orderId}: {ex.Message}"); |
| | | 1073 | | } |
| | | 1074 | | } |
| | | 1075 | | |
| | 0 | 1076 | | foreach (var (orderId, warehouseName, errorMessage) in failedTransactions) |
| | | 1077 | | { |
| | | 1078 | | try |
| | | 1079 | | { |
| | 0 | 1080 | | var resultId = await _loggingService.LogTransactionResultAsync( |
| | 0 | 1081 | | executionId, stepId, null, orderId, warehouseName, |
| | 0 | 1082 | | null, "Failed", null, cancellationToken); |
| | | 1083 | | |
| | 0 | 1084 | | await _loggingService.UpdateTransactionResultAsync( |
| | 0 | 1085 | | resultId, errorMessage: errorMessage, status: "Failed", cancellationToken: cancellationToken); |
| | | 1086 | | |
| | 0 | 1087 | | resultIds.Add(resultId); |
| | 0 | 1088 | | } |
| | 0 | 1089 | | catch (Exception ex) |
| | | 1090 | | { |
| | 0 | 1091 | | await SendLogAsync(jobId, $"✗ Ошибка логирования ошибки для заказа {orderId}: {ex.Message}"); |
| | | 1092 | | } |
| | 0 | 1093 | | } |
| | | 1094 | | |
| | 0 | 1095 | | return resultIds; |
| | 0 | 1096 | | } |
| | | 1097 | | |
| | | 1098 | | private async Task<(int successCount, int failCount)> PostTransactionsTo1CAsync( |
| | | 1099 | | long executionId, |
| | | 1100 | | long stepId, |
| | | 1101 | | List<long> transactionResultIds, |
| | | 1102 | | IReadOnlyDictionary<int, string> senderWarehouseByOrderId, |
| | | 1103 | | DateTime oneCOperationDate, |
| | | 1104 | | string? jobId, |
| | | 1105 | | CancellationToken cancellationToken) |
| | | 1106 | | { |
| | 0 | 1107 | | int successCount = 0; |
| | 0 | 1108 | | int failCount = 0; |
| | | 1109 | | |
| | 0 | 1110 | | var results = await _context.BackgroundTransactionResults |
| | 0 | 1111 | | .Where(r => transactionResultIds.Contains(r.Id)) |
| | 0 | 1112 | | .OrderBy(r => r.CreatedAt) |
| | 0 | 1113 | | .ToListAsync(cancellationToken); |
| | | 1114 | | |
| | 0 | 1115 | | var systemOnlyResults = results |
| | 0 | 1116 | | .Where(r => string.Equals(r.Status, "SystemOnly", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 1117 | | .ToList(); |
| | 0 | 1118 | | if (systemOnlyResults.Any()) |
| | | 1119 | | { |
| | 0 | 1120 | | successCount += systemOnlyResults.Count; |
| | 0 | 1121 | | foreach (var result in systemOnlyResults) |
| | | 1122 | | { |
| | 0 | 1123 | | await SendLogAsync(jobId, $"✓ Заказ {result.OrderId} проведён только в системе, 1С пропущена"); |
| | | 1124 | | } |
| | | 1125 | | } |
| | | 1126 | | |
| | 0 | 1127 | | var resultsToPost = results |
| | 0 | 1128 | | .Where(r => r.Status != "Failed" |
| | 0 | 1129 | | && r.TransactionId.HasValue |
| | 0 | 1130 | | && !string.Equals(r.Status, "PostedTo1C", StringComparison.OrdinalIgnoreCase) |
| | 0 | 1131 | | && !string.Equals(r.Status, "SystemOnly", StringComparison.OrdinalIgnoreCase) |
| | 0 | 1132 | | && string.IsNullOrEmpty(r.OneCDocumentId)) // dedup: не повторять уже задокументированные |
| | 0 | 1133 | | .GroupBy(r => r.TransactionId!.Value) |
| | 0 | 1134 | | .ToList(); |
| | | 1135 | | |
| | 0 | 1136 | | foreach (var transactionGroup in resultsToPost) |
| | | 1137 | | { |
| | 0 | 1138 | | var transactionId = transactionGroup.Key; |
| | 0 | 1139 | | var orderIds = transactionGroup.Select(r => r.OrderId).Distinct().ToArray(); |
| | 0 | 1140 | | var orders = await _orderServices.GetOrdersNoTracking(orderIds); |
| | 0 | 1141 | | if (!orders.Any()) |
| | | 1142 | | { |
| | 0 | 1143 | | await _loggingService.BulkUpdateTransactionResultsAsync( |
| | 0 | 1144 | | transactionGroup.Select(r => ( |
| | 0 | 1145 | | resultId: r.Id, |
| | 0 | 1146 | | transactionId: (int?)transactionId, |
| | 0 | 1147 | | oneCDocumentId: (string?)null, |
| | 0 | 1148 | | oneCDocumentNumber: (string?)null, |
| | 0 | 1149 | | status: (string?)"Failed", |
| | 0 | 1150 | | errorMessage: (string?)"Не удалось загрузить заказы для проведения в 1С", |
| | 0 | 1151 | | comment: (string?)null, |
| | 0 | 1152 | | isPosted: (bool?)null)), |
| | 0 | 1153 | | cancellationToken); |
| | 0 | 1154 | | failCount++; |
| | 0 | 1155 | | continue; |
| | | 1156 | | } |
| | | 1157 | | |
| | 0 | 1158 | | var orderWarehouseMap = new Dictionary<int, string>(); |
| | 0 | 1159 | | foreach (var order in orders) |
| | | 1160 | | { |
| | 0 | 1161 | | if (senderWarehouseByOrderId.TryGetValue(order.Id, out var warehouseName) && |
| | 0 | 1162 | | !string.IsNullOrWhiteSpace(warehouseName)) |
| | | 1163 | | { |
| | 0 | 1164 | | orderWarehouseMap[order.Id] = warehouseName; |
| | | 1165 | | } |
| | | 1166 | | } |
| | | 1167 | | |
| | | 1168 | | try |
| | | 1169 | | { |
| | 0 | 1170 | | await SendLogAsync(jobId, $"Проведение в 1С транзакции ID {transactionId} для {orders.Count} заказов..." |
| | | 1171 | | |
| | 0 | 1172 | | var maxRetries = 3; |
| | 0 | 1173 | | var retryDelay = TimeSpan.FromSeconds(5); |
| | 0 | 1174 | | List<OneCResponse> transferResult = []; |
| | 0 | 1175 | | Exception? lastException = null; |
| | | 1176 | | |
| | 0 | 1177 | | for (var attempt = 1; attempt <= maxRetries; attempt++) |
| | | 1178 | | { |
| | | 1179 | | try |
| | | 1180 | | { |
| | 0 | 1181 | | transferResult = await _oneCTransferManager.TransferStockByWarehousesWithReversedWarehouses( |
| | 0 | 1182 | | orders, |
| | 0 | 1183 | | TransactionType.ShippedToCommissioner, |
| | 0 | 1184 | | orderWarehouseMap, |
| | 0 | 1185 | | oneCOperationDate, |
| | 0 | 1186 | | SystemUserName); |
| | 0 | 1187 | | lastException = null; |
| | 0 | 1188 | | break; |
| | | 1189 | | } |
| | | 1190 | | catch (Exception ex) |
| | | 1191 | | { |
| | 0 | 1192 | | lastException = ex; |
| | 0 | 1193 | | var detail = FormatExceptionDetail(ex); |
| | 0 | 1194 | | Console.WriteLine($"[AutomatedTransactionProcessing] 1C posting failed (attempt {attempt}/{maxRe |
| | 0 | 1195 | | if (attempt < maxRetries) |
| | | 1196 | | { |
| | 0 | 1197 | | await Task.Delay(retryDelay, cancellationToken); |
| | | 1198 | | } |
| | | 1199 | | } |
| | | 1200 | | } |
| | | 1201 | | |
| | 0 | 1202 | | if (lastException != null) |
| | | 1203 | | { |
| | 0 | 1204 | | var errorMessage = $"1C posting failed after {maxRetries} attempts: {FormatExceptionDetail(lastExcep |
| | 0 | 1205 | | await _loggingService.BulkUpdateTransactionResultsAsync( |
| | 0 | 1206 | | transactionGroup.Select(r => ( |
| | 0 | 1207 | | resultId: r.Id, |
| | 0 | 1208 | | transactionId: (int?)transactionId, |
| | 0 | 1209 | | oneCDocumentId: (string?)null, |
| | 0 | 1210 | | oneCDocumentNumber: (string?)null, |
| | 0 | 1211 | | status: (string?)"Failed", |
| | 0 | 1212 | | errorMessage: (string?)errorMessage, |
| | 0 | 1213 | | comment: (string?)null, |
| | 0 | 1214 | | isPosted: (bool?)null)), |
| | 0 | 1215 | | cancellationToken); |
| | 0 | 1216 | | await SendLogAsync(jobId, $"✗ Ошибка проведения в 1С для транзакции {transactionId}: {FormatExceptio |
| | 0 | 1217 | | failCount += transactionGroup.Count(); |
| | 0 | 1218 | | continue; |
| | | 1219 | | } |
| | | 1220 | | |
| | 0 | 1221 | | var successfulTransfers = transferResult.Where(tr => tr.Success).ToList(); |
| | 0 | 1222 | | var failedTransfers = transferResult.Where(tr => !tr.Success).ToList(); |
| | 0 | 1223 | | if (!successfulTransfers.Any()) |
| | | 1224 | | { |
| | 0 | 1225 | | var errorMessage = failedTransfers.Any() |
| | 0 | 1226 | | ? string.Join("; ", failedTransfers.Select(f => f.Message).Distinct().Take(3)) |
| | 0 | 1227 | | : "1C не вернул успешный документ"; |
| | 0 | 1228 | | errorMessage = OneCResponseErrors.AppendOneCDetails(errorMessage, failedTransfers) ?? errorMessage; |
| | | 1229 | | |
| | 0 | 1230 | | await _loggingService.BulkUpdateTransactionResultsAsync( |
| | 0 | 1231 | | transactionGroup.Select(r => ( |
| | 0 | 1232 | | resultId: r.Id, |
| | 0 | 1233 | | transactionId: (int?)transactionId, |
| | 0 | 1234 | | oneCDocumentId: (string?)null, |
| | 0 | 1235 | | oneCDocumentNumber: (string?)null, |
| | 0 | 1236 | | status: (string?)"Failed", |
| | 0 | 1237 | | errorMessage: (string?)errorMessage, |
| | 0 | 1238 | | comment: (string?)null, |
| | 0 | 1239 | | isPosted: (bool?)null)), |
| | 0 | 1240 | | cancellationToken); |
| | 0 | 1241 | | await SendLogAsync(jobId, $"✗ Ошибка проведения в 1С для транзакции {transactionId}: {errorMessage}" |
| | 0 | 1242 | | failCount += transactionGroup.Count(); |
| | 0 | 1243 | | continue; |
| | | 1244 | | } |
| | | 1245 | | |
| | 0 | 1246 | | var oneCDocumentIds = successfulTransfers |
| | 0 | 1247 | | .Select(tr => tr.TransactionId) // GUID Ref_Key |
| | 0 | 1248 | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | 0 | 1249 | | .Distinct() |
| | 0 | 1250 | | .ToArray(); |
| | 0 | 1251 | | var oneCDocumentNumbers = successfulTransfers |
| | 0 | 1252 | | .Select(tr => !string.IsNullOrWhiteSpace(tr.DocumentNumber) ? tr.DocumentNumber : tr.TransactionId) |
| | 0 | 1253 | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | 0 | 1254 | | .Distinct() |
| | 0 | 1255 | | .ToArray(); |
| | | 1256 | | |
| | 0 | 1257 | | if (oneCDocumentNumbers.Any()) |
| | | 1258 | | { |
| | 0 | 1259 | | await _transactionDataServices.UpdateTransactionComment( |
| | 0 | 1260 | | transactionId, |
| | 0 | 1261 | | string.Join(", ", oneCDocumentNumbers)); |
| | | 1262 | | } |
| | | 1263 | | |
| | 0 | 1264 | | var documentId = successfulTransfers.First().TransactionId; // GUID |
| | 0 | 1265 | | var documentNumber = !string.IsNullOrWhiteSpace(successfulTransfers.First().DocumentNumber) |
| | 0 | 1266 | | ? successfulTransfers.First().DocumentNumber |
| | 0 | 1267 | | : successfulTransfers.First().TransactionId; |
| | 0 | 1268 | | if (successfulTransfers.Count > 1) |
| | | 1269 | | { |
| | 0 | 1270 | | await SendLogAsync(jobId, $"⚠️ Транзакция {transactionId} вернула {successfulTransfers.Count} докуме |
| | | 1271 | | } |
| | | 1272 | | |
| | 0 | 1273 | | var allPosted = successfulTransfers.All(tr => tr.IsPosted); |
| | 0 | 1274 | | var missingNom = string.Join("; ", |
| | 0 | 1275 | | successfulTransfers |
| | 0 | 1276 | | .Where(tr => !string.IsNullOrWhiteSpace(tr.MissingNomenclature)) |
| | 0 | 1277 | | .Select(tr => tr.MissingNomenclature) |
| | 0 | 1278 | | .Distinct()); |
| | 0 | 1279 | | var postingErrors = string.Join("; ", |
| | 0 | 1280 | | successfulTransfers |
| | 0 | 1281 | | .Where(tr => !tr.IsPosted && !string.IsNullOrWhiteSpace(tr.PostingError)) |
| | 0 | 1282 | | .Select(tr => tr.PostingError) |
| | 0 | 1283 | | .Distinct()); |
| | 0 | 1284 | | var draftDetail = !string.IsNullOrWhiteSpace(postingErrors) |
| | 0 | 1285 | | ? postingErrors |
| | 0 | 1286 | | : !string.IsNullOrWhiteSpace(missingNom) |
| | 0 | 1287 | | ? $"не найдена номенклатура: {missingNom}" |
| | 0 | 1288 | | : allPosted ? null : "документ не проведён в 1С (черновик)"; |
| | 0 | 1289 | | if (!allPosted) |
| | 0 | 1290 | | draftDetail = OneCResponseErrors.AppendOneCDetails(draftDetail, successfulTransfers.Where(tr => !tr. |
| | | 1291 | | |
| | 0 | 1292 | | await _loggingService.BulkUpdateTransactionResultsAsync( |
| | 0 | 1293 | | transactionGroup.Select(r => ( |
| | 0 | 1294 | | resultId: r.Id, |
| | 0 | 1295 | | transactionId: (int?)transactionId, |
| | 0 | 1296 | | oneCDocumentId: documentId, // GUID |
| | 0 | 1297 | | oneCDocumentNumber: documentNumber, // НФY1-001620 |
| | 0 | 1298 | | status: (string?)(allPosted ? "PostedTo1C" : "DraftIn1C"), |
| | 0 | 1299 | | errorMessage: (string?)(allPosted ? null : draftDetail), |
| | 0 | 1300 | | comment: oneCDocumentNumbers.Any() ? string.Join(", ", oneCDocumentNumbers) : documentNumber, |
| | 0 | 1301 | | isPosted: (bool?)allPosted)), |
| | 0 | 1302 | | cancellationToken); |
| | | 1303 | | |
| | 0 | 1304 | | var historyWindowStart = DateTime.UtcNow.AddMinutes(-30); |
| | 0 | 1305 | | var historySenderWarehouses = orders |
| | 0 | 1306 | | .Select(o => orderWarehouseMap.TryGetValue(o.Id, out var w) ? w : null) |
| | 0 | 1307 | | .Where(w => !string.IsNullOrWhiteSpace(w)) |
| | 0 | 1308 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 1309 | | .ToList(); |
| | 0 | 1310 | | var historyRecipient = orders |
| | 0 | 1311 | | .Select(o => o.OzonClient?.WarehouseName?.Trim()) |
| | 0 | 1312 | | .FirstOrDefault(w => !string.IsNullOrWhiteSpace(w)); |
| | 0 | 1313 | | await TryRecordOneCHistoryMovementAsync( |
| | 0 | 1314 | | orders, |
| | 0 | 1315 | | transferResult, |
| | 0 | 1316 | | transactionId, |
| | 0 | 1317 | | historyWindowStart, |
| | 0 | 1318 | | historySenderWarehouses.Count > 0 ? string.Join(", ", historySenderWarehouses) : null, |
| | 0 | 1319 | | historyRecipient); |
| | | 1320 | | |
| | 0 | 1321 | | successCount += transactionGroup.Count(); |
| | 0 | 1322 | | if (!allPosted) |
| | | 1323 | | { |
| | 0 | 1324 | | await SendLogAsync(jobId, |
| | 0 | 1325 | | $"⚠ 1С черновик для транзакции {transactionId}: {documentNumber} ({draftDetail})"); |
| | | 1326 | | } |
| | | 1327 | | else |
| | | 1328 | | { |
| | 0 | 1329 | | await SendLogAsync(jobId, $"✓ 1С документ создан для транзакции {transactionId}: {documentNumber}"); |
| | | 1330 | | } |
| | 0 | 1331 | | } |
| | 0 | 1332 | | catch (Exception ex) |
| | | 1333 | | { |
| | 0 | 1334 | | var detail = FormatExceptionDetail(ex); |
| | 0 | 1335 | | Console.WriteLine($"[AutomatedTransactionProcessing] 1C posting error for transaction {transactionId}: { |
| | 0 | 1336 | | await _loggingService.BulkUpdateTransactionResultsAsync( |
| | 0 | 1337 | | transactionGroup.Select(r => ( |
| | 0 | 1338 | | resultId: r.Id, |
| | 0 | 1339 | | transactionId: (int?)transactionId, |
| | 0 | 1340 | | oneCDocumentId: (string?)null, |
| | 0 | 1341 | | oneCDocumentNumber: (string?)null, |
| | 0 | 1342 | | status: (string?)"Failed", |
| | 0 | 1343 | | errorMessage: (string?)detail, |
| | 0 | 1344 | | comment: (string?)null, |
| | 0 | 1345 | | isPosted: (bool?)null)), |
| | 0 | 1346 | | cancellationToken); |
| | 0 | 1347 | | await SendLogAsync(jobId, $"✗ Ошибка проведения в 1С для транзакции {transactionId}: {detail}"); |
| | 0 | 1348 | | failCount += transactionGroup.Count(); |
| | 0 | 1349 | | } |
| | 0 | 1350 | | } |
| | | 1351 | | |
| | 0 | 1352 | | return (successCount, failCount); |
| | 0 | 1353 | | } |
| | | 1354 | | |
| | | 1355 | | private async Task<List<Order>> MatchOrdersByShipmentAsync( |
| | | 1356 | | long executionId, |
| | | 1357 | | long stepId, |
| | | 1358 | | int ozonClientId, |
| | | 1359 | | List<string> shipmentNumbers, |
| | | 1360 | | CancellationToken cancellationToken) |
| | | 1361 | | { |
| | 0 | 1362 | | var cleanShipments = shipmentNumbers |
| | 0 | 1363 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 0 | 1364 | | .Select(x => x.Trim()) |
| | 0 | 1365 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 1366 | | .ToList(); |
| | | 1367 | | |
| | 0 | 1368 | | if (cleanShipments.Count == 0) |
| | 0 | 1369 | | return []; |
| | | 1370 | | |
| | 0 | 1371 | | var (orderIds, matchedShipments) = await _orderServices.GetOrderIdsAndMatchedShipmentsByShipmentListAsync(cleanS |
| | 0 | 1372 | | var orders = await _orderServices.GetOrdersNoTracking(orderIds.ToArray()); |
| | 0 | 1373 | | var ordersByShipment = orders |
| | 0 | 1374 | | .GroupBy(o => _orderServices.NormalizeOrderNumberForMatching(o.ShipmentNumber), |
| | 0 | 1375 | | StringComparer.OrdinalIgnoreCase) |
| | 0 | 1376 | | .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); |
| | | 1377 | | |
| | 0 | 1378 | | var matches = new List<BackgroundOrderMatch>(cleanShipments.Count); |
| | 0 | 1379 | | foreach (var shipment in cleanShipments) |
| | | 1380 | | { |
| | 0 | 1381 | | var normalized = _orderServices.NormalizeOrderNumberForMatching(shipment); |
| | | 1382 | | // Одному отправлению может соответствовать несколько строк заказа («…-1/1», «…-1/2»), |
| | | 1383 | | // и каждая должна попасть в лог сопоставления. |
| | 0 | 1384 | | var shipmentOrders = ordersByShipment.GetValueOrDefault(normalized) ?? []; |
| | 0 | 1385 | | var isMatched = shipmentOrders.Count > 0 || matchedShipments.Contains(shipment.Trim()); |
| | | 1386 | | |
| | 0 | 1387 | | if (shipmentOrders.Count == 0) |
| | | 1388 | | { |
| | 0 | 1389 | | matches.Add(new BackgroundOrderMatch |
| | 0 | 1390 | | { |
| | 0 | 1391 | | ExecutionId = executionId, |
| | 0 | 1392 | | StepId = stepId, |
| | 0 | 1393 | | OrderNumber = shipment, |
| | 0 | 1394 | | Article = shipment, |
| | 0 | 1395 | | OrderId = null, |
| | 0 | 1396 | | OrderStatus = null, |
| | 0 | 1397 | | IsMatchedInDb = isMatched, |
| | 0 | 1398 | | IsEligibleForProcessing = false, |
| | 0 | 1399 | | RejectionReason = isMatched ? null : "Заказ не найден в БД", |
| | 0 | 1400 | | CreatedAt = DateTime.UtcNow |
| | 0 | 1401 | | }); |
| | 0 | 1402 | | continue; |
| | | 1403 | | } |
| | | 1404 | | |
| | 0 | 1405 | | foreach (var order in shipmentOrders) |
| | | 1406 | | { |
| | 0 | 1407 | | matches.Add(new BackgroundOrderMatch |
| | 0 | 1408 | | { |
| | 0 | 1409 | | ExecutionId = executionId, |
| | 0 | 1410 | | StepId = stepId, |
| | 0 | 1411 | | OrderNumber = shipment, |
| | 0 | 1412 | | Article = shipment, |
| | 0 | 1413 | | OrderId = order.Id, |
| | 0 | 1414 | | OrderStatus = order.AppStatus?.Name ?? order.Status, |
| | 0 | 1415 | | IsMatchedInDb = true, |
| | 0 | 1416 | | IsEligibleForProcessing = true, |
| | 0 | 1417 | | RejectionReason = null, |
| | 0 | 1418 | | CreatedAt = DateTime.UtcNow |
| | 0 | 1419 | | }); |
| | | 1420 | | } |
| | | 1421 | | } |
| | | 1422 | | |
| | 0 | 1423 | | await _loggingService.BulkLogOrderMatchesAsync(matches, cancellationToken); |
| | 0 | 1424 | | return orders; |
| | 0 | 1425 | | } |
| | | 1426 | | |
| | | 1427 | | private async Task<(List<Order> readyOrders, int skippedCount, string senderWarehouse, Dictionary<int, string> recip |
| | | 1428 | | ResolveCustomerReturnWarehousesAsync( |
| | | 1429 | | long executionId, |
| | | 1430 | | long stepId, |
| | | 1431 | | List<Order> eligibleOrders, |
| | | 1432 | | string? jobId, |
| | | 1433 | | CancellationToken cancellationToken) |
| | | 1434 | | { |
| | 0 | 1435 | | var readyOrders = new List<Order>(); |
| | 0 | 1436 | | var recipientByOrderId = new Dictionary<int, string>(); |
| | 0 | 1437 | | var skippedCount = 0; |
| | | 1438 | | |
| | 0 | 1439 | | if (!eligibleOrders.Any()) |
| | 0 | 1440 | | return (readyOrders, skippedCount, string.Empty, recipientByOrderId); |
| | | 1441 | | |
| | | 1442 | | // Batch-load matches once for all eligible orders |
| | 0 | 1443 | | var orderIds = eligibleOrders.Select(o => o.Id).ToList(); |
| | 0 | 1444 | | var allMatches = await _context.BackgroundOrderMatches |
| | 0 | 1445 | | .Where(m => m.ExecutionId == executionId && m.OrderId != null && orderIds.Contains(m.OrderId.Value)) |
| | 0 | 1446 | | .OrderByDescending(m => m.CreatedAt) |
| | 0 | 1447 | | .ToListAsync(cancellationToken); |
| | 0 | 1448 | | var matchByOrderId = allMatches |
| | 0 | 1449 | | .GroupBy(m => m.OrderId!.Value) |
| | 0 | 1450 | | .ToDictionary(g => g.Key, g => g.First()); |
| | | 1451 | | |
| | 0 | 1452 | | var senderResolution = await _warehouseSelectionResolver.ResolveSenderWarehouseAsync(eligibleOrders); |
| | 0 | 1453 | | if (senderResolution.HasErrors || string.IsNullOrWhiteSpace(senderResolution.SenderWarehouseName)) |
| | | 1454 | | { |
| | 0 | 1455 | | var reason = senderResolution.HasErrors |
| | 0 | 1456 | | ? string.Join("; ", senderResolution.Errors.Distinct()) |
| | 0 | 1457 | | : "Не удалось определить склад отправителя (склад покупателя Ozon)."; |
| | 0 | 1458 | | await SendLogAsync(jobId, $"✗ Склад отправителя не определён: {reason}"); |
| | 0 | 1459 | | foreach (var order in eligibleOrders) |
| | | 1460 | | { |
| | 0 | 1461 | | skippedCount++; |
| | 0 | 1462 | | matchByOrderId.TryGetValue(order.Id, out var match); |
| | 0 | 1463 | | await LogCustomerReturnSkippedAsync(executionId, stepId, order, null, reason, match, cancellationToken); |
| | | 1464 | | } |
| | | 1465 | | |
| | 0 | 1466 | | await _context.SaveChangesAsync(cancellationToken); |
| | 0 | 1467 | | return (readyOrders, skippedCount, string.Empty, recipientByOrderId); |
| | | 1468 | | } |
| | | 1469 | | |
| | 0 | 1470 | | var senderWarehouse = senderResolution.SenderWarehouseName.Trim(); |
| | 0 | 1471 | | await SendLogAsync(jobId, $"Склад отправителя (покупатель): {senderWarehouse}"); |
| | | 1472 | | |
| | 0 | 1473 | | var recipientResolution = await _warehouseSelectionResolver.ResolveCustomerReturnRecipientByOrderAsync(eligibleO |
| | 0 | 1474 | | foreach (var order in eligibleOrders) |
| | | 1475 | | { |
| | 0 | 1476 | | if (recipientResolution.RecipientByOrderId.TryGetValue(order.Id, out var recipient)) |
| | | 1477 | | { |
| | 0 | 1478 | | recipient = recipient.Trim(); |
| | 0 | 1479 | | if (string.Equals(senderWarehouse, recipient, StringComparison.OrdinalIgnoreCase)) |
| | | 1480 | | { |
| | 0 | 1481 | | skippedCount++; |
| | 0 | 1482 | | var sameWhReason = $"Склад отправителя и получателя совпадают ('{senderWarehouse}')"; |
| | 0 | 1483 | | await SendLogAsync(jobId, $"⊘ {order.ShipmentNumber}: {sameWhReason}"); |
| | 0 | 1484 | | matchByOrderId.TryGetValue(order.Id, out var match); |
| | 0 | 1485 | | await LogCustomerReturnSkippedAsync(executionId, stepId, order, recipient, sameWhReason, match, canc |
| | 0 | 1486 | | continue; |
| | | 1487 | | } |
| | | 1488 | | |
| | 0 | 1489 | | recipientByOrderId[order.Id] = recipient; |
| | 0 | 1490 | | readyOrders.Add(order); |
| | 0 | 1491 | | await SendLogAsync(jobId, $"✓ {order.ShipmentNumber}: {senderWarehouse} → {recipient}"); |
| | 0 | 1492 | | continue; |
| | | 1493 | | } |
| | | 1494 | | |
| | 0 | 1495 | | skippedCount++; |
| | 0 | 1496 | | var orderReason = recipientResolution.BlockingErrors |
| | 0 | 1497 | | .FirstOrDefault(e => e.Contains(order.ShipmentNumber ?? order.Id.ToString(), StringComparison.OrdinalIgn |
| | 0 | 1498 | | ?? "Не найден маппинг склада получателя (WarehouseMappings)"; |
| | 0 | 1499 | | await SendLogAsync(jobId, $"⊘ {order.ShipmentNumber}: {orderReason}"); |
| | 0 | 1500 | | matchByOrderId.TryGetValue(order.Id, out var skipMatch); |
| | 0 | 1501 | | await LogCustomerReturnSkippedAsync(executionId, stepId, order, null, orderReason, skipMatch, cancellationTo |
| | 0 | 1502 | | } |
| | | 1503 | | |
| | 0 | 1504 | | if (skippedCount > 0) |
| | 0 | 1505 | | await _context.SaveChangesAsync(cancellationToken); // batch save after all skips |
| | | 1506 | | |
| | 0 | 1507 | | return (readyOrders, skippedCount, senderWarehouse, recipientByOrderId); |
| | 0 | 1508 | | } |
| | | 1509 | | |
| | | 1510 | | private async Task<List<long>> ApplyCommissionerStatusOnlyAsync( |
| | | 1511 | | long executionId, |
| | | 1512 | | long stepId, |
| | | 1513 | | List<Order> orders, |
| | | 1514 | | string warehouseName, |
| | | 1515 | | int? scheduleId, |
| | | 1516 | | AppStatus commissionerStatus, |
| | | 1517 | | string? jobId, |
| | | 1518 | | CancellationToken cancellationToken) |
| | | 1519 | | { |
| | 0 | 1520 | | var resultIds = new List<long>(); |
| | 0 | 1521 | | if (!orders.Any()) |
| | | 1522 | | { |
| | 0 | 1523 | | return resultIds; |
| | | 1524 | | } |
| | | 1525 | | |
| | 0 | 1526 | | var comment = BuildAutomatedCommissionerComment(scheduleId) + |
| | 0 | 1527 | | $" ({SellerStatusName}: только смена статуса, без документа и 1С)"; |
| | 0 | 1528 | | var performedAt = DateTime.UtcNow; |
| | 0 | 1529 | | var fromStatusByOrderId = orders.ToDictionary(o => o.Id, o => o.AppStatusId ?? 0); |
| | 0 | 1530 | | ApplySystemAttribution(orders); |
| | 0 | 1531 | | ClearOrderNavigationForPersist(orders); |
| | | 1532 | | |
| | 0 | 1533 | | foreach (var order in orders) |
| | | 1534 | | { |
| | 0 | 1535 | | if (!string.Equals(order.Status, "Отменен", StringComparison.OrdinalIgnoreCase)) |
| | | 1536 | | { |
| | 0 | 1537 | | order.AppStatusId = commissionerStatus.Id; |
| | 0 | 1538 | | order.AppStatus = commissionerStatus; |
| | | 1539 | | } |
| | | 1540 | | } |
| | | 1541 | | |
| | | 1542 | | try |
| | | 1543 | | { |
| | 0 | 1544 | | foreach (var order in orders) |
| | | 1545 | | { |
| | 0 | 1546 | | order.AppStatus = null; |
| | | 1547 | | } |
| | | 1548 | | |
| | 0 | 1549 | | await _orderServices.UpdateOrders(orders); |
| | 0 | 1550 | | await TryRecordStatusTransitionHistoryAsync( |
| | 0 | 1551 | | TransactionType.ShippedToCommissioner, |
| | 0 | 1552 | | orders, |
| | 0 | 1553 | | fromStatusByOrderId, |
| | 0 | 1554 | | comment, |
| | 0 | 1555 | | performedAt, |
| | 0 | 1556 | | cancellationToken); |
| | | 1557 | | |
| | 0 | 1558 | | var numbers = string.Join(", ", orders |
| | 0 | 1559 | | .Select(o => o.ShipmentNumber) |
| | 0 | 1560 | | .Where(n => !string.IsNullOrWhiteSpace(n)) |
| | 0 | 1561 | | .Distinct(StringComparer.OrdinalIgnoreCase)); |
| | 0 | 1562 | | await SendLogAsync(jobId, |
| | 0 | 1563 | | $"✓ Склад '{warehouseName}': смена статуса без документа для {orders.Count} заказ(ов){(string.IsNullOrWh |
| | | 1564 | | |
| | 0 | 1565 | | foreach (var order in orders) |
| | | 1566 | | { |
| | 0 | 1567 | | var resultId = await _loggingService.LogTransactionResultAsync( |
| | 0 | 1568 | | executionId, |
| | 0 | 1569 | | stepId, |
| | 0 | 1570 | | null, |
| | 0 | 1571 | | order.Id, |
| | 0 | 1572 | | warehouseName, |
| | 0 | 1573 | | null, |
| | 0 | 1574 | | "SystemOnly", |
| | 0 | 1575 | | $"Статус '{SellerStatusName}': смена на '{CommissionerStatusName}' без документа транзакции и без 1С |
| | 0 | 1576 | | cancellationToken); |
| | 0 | 1577 | | resultIds.Add(resultId); |
| | | 1578 | | } |
| | 0 | 1579 | | } |
| | 0 | 1580 | | catch (Exception ex) |
| | | 1581 | | { |
| | 0 | 1582 | | var errorMessage = FormatExceptionDetail(ex); |
| | 0 | 1583 | | await SendLogAsync(jobId, $"✗ Ошибка смены статуса для склада '{warehouseName}': {errorMessage}"); |
| | 0 | 1584 | | foreach (var order in orders) |
| | | 1585 | | { |
| | 0 | 1586 | | var resultId = await _loggingService.LogTransactionResultAsync( |
| | 0 | 1587 | | executionId, stepId, null, order.Id, warehouseName, |
| | 0 | 1588 | | null, "Failed", null, cancellationToken); |
| | 0 | 1589 | | await _loggingService.UpdateTransactionResultAsync( |
| | 0 | 1590 | | resultId, errorMessage: errorMessage, status: "Failed", cancellationToken: cancellationToken); |
| | 0 | 1591 | | resultIds.Add(resultId); |
| | | 1592 | | } |
| | 0 | 1593 | | } |
| | | 1594 | | |
| | 0 | 1595 | | return resultIds; |
| | 0 | 1596 | | } |
| | | 1597 | | |
| | | 1598 | | private async Task LogCommissionerProcessingSkippedAsync( |
| | | 1599 | | long executionId, |
| | | 1600 | | long stepId, |
| | | 1601 | | Order order, |
| | | 1602 | | string? warehouseName, |
| | | 1603 | | string reason, |
| | | 1604 | | BackgroundOrderMatch? preloadedMatch, |
| | | 1605 | | CancellationToken cancellationToken) |
| | | 1606 | | { |
| | 0 | 1607 | | if (preloadedMatch != null) |
| | | 1608 | | { |
| | 0 | 1609 | | preloadedMatch.IsEligibleForProcessing = false; |
| | 0 | 1610 | | preloadedMatch.RejectionReason = reason.Length > 500 ? reason[..500] : reason; |
| | | 1611 | | } |
| | | 1612 | | |
| | 0 | 1613 | | await _loggingService.LogTransactionResultAsync( |
| | 0 | 1614 | | executionId, |
| | 0 | 1615 | | stepId, |
| | 0 | 1616 | | preloadedMatch?.Id, |
| | 0 | 1617 | | order.Id, |
| | 0 | 1618 | | warehouseName, |
| | 0 | 1619 | | null, |
| | 0 | 1620 | | "Skipped", |
| | 0 | 1621 | | reason, |
| | 0 | 1622 | | cancellationToken); |
| | 0 | 1623 | | } |
| | | 1624 | | |
| | | 1625 | | private async Task LogCustomerReturnSkippedAsync( |
| | | 1626 | | long executionId, |
| | | 1627 | | long stepId, |
| | | 1628 | | Order order, |
| | | 1629 | | string? recipientWarehouse, |
| | | 1630 | | string reason, |
| | | 1631 | | BackgroundOrderMatch? preloadedMatch, |
| | | 1632 | | CancellationToken cancellationToken) |
| | | 1633 | | { |
| | 0 | 1634 | | if (preloadedMatch != null) |
| | | 1635 | | { |
| | 0 | 1636 | | preloadedMatch.IsEligibleForProcessing = false; |
| | 0 | 1637 | | preloadedMatch.RejectionReason = reason.Length > 500 ? reason[..500] : reason; |
| | | 1638 | | } |
| | | 1639 | | |
| | 0 | 1640 | | await _loggingService.LogTransactionResultAsync( |
| | 0 | 1641 | | executionId, |
| | 0 | 1642 | | stepId, |
| | 0 | 1643 | | preloadedMatch?.Id, |
| | 0 | 1644 | | order.Id, |
| | 0 | 1645 | | recipientWarehouse, |
| | 0 | 1646 | | null, |
| | 0 | 1647 | | "Skipped", |
| | 0 | 1648 | | reason, |
| | 0 | 1649 | | cancellationToken); |
| | 0 | 1650 | | } |
| | | 1651 | | |
| | | 1652 | | private async Task<(int processedCount, int failedCount)> ProcessCustomerReturnWithOneCAsync( |
| | | 1653 | | long executionId, |
| | | 1654 | | long stepId, |
| | | 1655 | | List<Order> readyOrders, |
| | | 1656 | | string senderWarehouse, |
| | | 1657 | | Dictionary<int, string> recipientByOrderId, |
| | | 1658 | | DateTime oneCOperationDate, |
| | | 1659 | | int? scheduleId, |
| | | 1660 | | string? jobId, |
| | | 1661 | | CancellationToken cancellationToken) |
| | | 1662 | | { |
| | 0 | 1663 | | if (!readyOrders.Any() || string.IsNullOrWhiteSpace(senderWarehouse)) |
| | 0 | 1664 | | return (0, 0); |
| | | 1665 | | |
| | 0 | 1666 | | var customerReturnStatus = await _appStatusServices.GetAppStatusAsync(new AppStatus { Name = CustomerReturnStatu |
| | 0 | 1667 | | if (customerReturnStatus == null) |
| | 0 | 1668 | | throw new Exception($"Не найден статус '{CustomerReturnStatusName}'"); |
| | | 1669 | | |
| | 0 | 1670 | | var processedCount = 0; |
| | 0 | 1671 | | var failedCount = 0; |
| | 0 | 1672 | | var groups = readyOrders |
| | 0 | 1673 | | .GroupBy(o => recipientByOrderId[o.Id], StringComparer.OrdinalIgnoreCase) |
| | 0 | 1674 | | .ToList(); |
| | | 1675 | | |
| | 0 | 1676 | | await SendLogAsync(jobId, $"Групп по складам получателя: {groups.Count}"); |
| | | 1677 | | |
| | 0 | 1678 | | foreach (var group in groups) |
| | | 1679 | | { |
| | 0 | 1680 | | var recipient = group.Key.Trim(); |
| | 0 | 1681 | | var groupOrders = group.ToList(); |
| | 0 | 1682 | | var shipmentList = string.Join(", ", groupOrders.Select(o => o.ShipmentNumber).Where(x => !string.IsNullOrWh |
| | 0 | 1683 | | await SendLogAsync(jobId, $"▶ Группа «{recipient}»: {groupOrders.Count} заказ(ов) ({shipmentList})"); |
| | | 1684 | | |
| | 0 | 1685 | | var ordersFor1C = await _orderServices.GetOrdersNoTracking(groupOrders.Select(o => o.Id).ToArray()); |
| | 0 | 1686 | | if (!ordersFor1C.Any()) |
| | | 1687 | | { |
| | 0 | 1688 | | foreach (var order in groupOrders) |
| | | 1689 | | { |
| | 0 | 1690 | | failedCount++; |
| | 0 | 1691 | | await LogCustomerReturnFailedAsync(executionId, stepId, order, recipient, |
| | 0 | 1692 | | "Не удалось загрузить заказы для проведения в 1С", null, cancellationToken); |
| | | 1693 | | } |
| | | 1694 | | |
| | 0 | 1695 | | continue; |
| | | 1696 | | } |
| | | 1697 | | |
| | | 1698 | | List<OneCResponse> transferResult; |
| | | 1699 | | try |
| | | 1700 | | { |
| | 0 | 1701 | | transferResult = await PostCustomerReturnTo1CWithRetryAsync( |
| | 0 | 1702 | | ordersFor1C, |
| | 0 | 1703 | | senderWarehouse, |
| | 0 | 1704 | | recipient, |
| | 0 | 1705 | | oneCOperationDate, |
| | 0 | 1706 | | jobId, |
| | 0 | 1707 | | cancellationToken); |
| | 0 | 1708 | | } |
| | 0 | 1709 | | catch (Exception ex) |
| | | 1710 | | { |
| | 0 | 1711 | | foreach (var order in groupOrders) |
| | | 1712 | | { |
| | 0 | 1713 | | failedCount++; |
| | 0 | 1714 | | await LogCustomerReturnFailedAsync(executionId, stepId, order, recipient, FormatExceptionDetail(ex), |
| | | 1715 | | } |
| | | 1716 | | |
| | 0 | 1717 | | continue; |
| | | 1718 | | } |
| | | 1719 | | |
| | 0 | 1720 | | var successfulTransfers = transferResult.Where(tr => tr.Success).ToList(); |
| | 0 | 1721 | | var failedTransfers = transferResult.Where(tr => !tr.Success).ToList(); |
| | | 1722 | | |
| | 0 | 1723 | | if (!successfulTransfers.Any()) |
| | | 1724 | | { |
| | 0 | 1725 | | var errorMessage = failedTransfers.Any() |
| | 0 | 1726 | | ? string.Join("; ", failedTransfers.Select(f => f.Message).Distinct().Take(3)) |
| | 0 | 1727 | | : "1С не вернул успешный документ"; |
| | 0 | 1728 | | await SendLogAsync(jobId, $"✗ 1С: группа «{recipient}» — {errorMessage}"); |
| | 0 | 1729 | | foreach (var order in groupOrders) |
| | | 1730 | | { |
| | 0 | 1731 | | failedCount++; |
| | 0 | 1732 | | await LogCustomerReturnFailedAsync(executionId, stepId, order, recipient, errorMessage, null, cancel |
| | | 1733 | | } |
| | | 1734 | | |
| | 0 | 1735 | | continue; |
| | | 1736 | | } |
| | | 1737 | | |
| | 0 | 1738 | | var oneCDocumentIds = successfulTransfers |
| | 0 | 1739 | | .Select(tr => tr.TransactionId) // GUID Ref_Key |
| | 0 | 1740 | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | 0 | 1741 | | .Distinct() |
| | 0 | 1742 | | .ToList(); |
| | | 1743 | | // Читаемые номера документов ("НФY1-001620") |
| | 0 | 1744 | | var oneCDocumentLabels = successfulTransfers |
| | 0 | 1745 | | .Select(tr => !string.IsNullOrWhiteSpace(tr.DocumentNumber) ? tr.DocumentNumber : tr.TransactionId) |
| | 0 | 1746 | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | 0 | 1747 | | .Distinct() |
| | 0 | 1748 | | .ToList(); |
| | 0 | 1749 | | var documentLabel = oneCDocumentLabels.Any() ? string.Join(", ", oneCDocumentLabels) : "—"; |
| | 0 | 1750 | | var groupIsPostedForLog = successfulTransfers.All(tr => tr.IsPosted); |
| | 0 | 1751 | | if (groupIsPostedForLog) |
| | | 1752 | | { |
| | 0 | 1753 | | await SendLogAsync(jobId, $"✓ 1С: группа «{recipient}» — документ(ы): {documentLabel}"); |
| | | 1754 | | } |
| | | 1755 | | else |
| | | 1756 | | { |
| | 0 | 1757 | | var postingErrors = string.Join("; ", |
| | 0 | 1758 | | successfulTransfers |
| | 0 | 1759 | | .Where(tr => !tr.IsPosted && !string.IsNullOrWhiteSpace(tr.PostingError)) |
| | 0 | 1760 | | .Select(tr => tr.PostingError) |
| | 0 | 1761 | | .Distinct()); |
| | 0 | 1762 | | var draftDetail = string.IsNullOrWhiteSpace(postingErrors) ? "документ не проведён" : postingErrors; |
| | 0 | 1763 | | await SendLogAsync(jobId, $"⚠ 1С: группа «{recipient}» — документ(ы): {documentLabel} ({draftDetail})"); |
| | | 1764 | | } |
| | | 1765 | | |
| | 0 | 1766 | | var trackedOrders = await _orderServices.GetOrdersByIdsTracked( |
| | 0 | 1767 | | groupOrders.Select(o => o.Id).Distinct().ToList(), includeArchived: false); |
| | 0 | 1768 | | if (!trackedOrders.Any()) |
| | | 1769 | | { |
| | 0 | 1770 | | foreach (var order in groupOrders) |
| | | 1771 | | { |
| | 0 | 1772 | | failedCount++; |
| | 0 | 1773 | | await LogCustomerReturnFailedAsync(executionId, stepId, order, recipient, |
| | 0 | 1774 | | "1С проведён, но не удалось обновить заказы в системе", null, cancellationToken); |
| | | 1775 | | } |
| | | 1776 | | |
| | 0 | 1777 | | continue; |
| | | 1778 | | } |
| | | 1779 | | |
| | | 1780 | | try |
| | | 1781 | | { |
| | 0 | 1782 | | var historyWindowStart = DateTime.UtcNow; |
| | 0 | 1783 | | var fromStatusByOrderId = trackedOrders.ToDictionary(o => o.Id, o => o.AppStatusId ?? 0); |
| | 0 | 1784 | | var performedAt = DateTime.UtcNow; |
| | 0 | 1785 | | var lastStatusChangeDate = TimeZoneInfo.ConvertTime(performedAt, RussianTimeZone); |
| | 0 | 1786 | | ApplySystemAttribution(trackedOrders); |
| | | 1787 | | |
| | 0 | 1788 | | foreach (var order in trackedOrders) |
| | | 1789 | | { |
| | 0 | 1790 | | order.AppStatusId = customerReturnStatus.Id; |
| | 0 | 1791 | | order.LastStatusChangeDate = lastStatusChangeDate; |
| | | 1792 | | } |
| | | 1793 | | |
| | 0 | 1794 | | var comment = $"Проведено автоматически системой {performedAt:yyyy-MM-dd HH:mm:ss} UTC" + |
| | 0 | 1795 | | (scheduleId.HasValue ? $" (расписание ID: {scheduleId.Value})" : " (ручной запуск)") + |
| | 0 | 1796 | | (oneCDocumentLabels.Any() |
| | 0 | 1797 | | ? $". 1С: {senderWarehouse} → {recipient}, dok. {string.Join(", ", oneCDocumentLabels) |
| | 0 | 1798 | | : $". 1С: {senderWarehouse} → {recipient}"); |
| | | 1799 | | |
| | 0 | 1800 | | var (_, _, transactionId) = await _transactionManager.CreateCustomerReturnTransaction( |
| | 0 | 1801 | | trackedOrders, |
| | 0 | 1802 | | SystemUserName, |
| | 0 | 1803 | | performedAt, |
| | 0 | 1804 | | comment); |
| | | 1805 | | |
| | 0 | 1806 | | if (oneCDocumentIds.Any()) |
| | | 1807 | | { |
| | 0 | 1808 | | await _transactionDataServices.UpdateTransactionComment( |
| | 0 | 1809 | | transactionId, |
| | 0 | 1810 | | comment); |
| | | 1811 | | } |
| | | 1812 | | |
| | 0 | 1813 | | var orderIds = trackedOrders.Select(o => o.Id).Distinct().ToList(); |
| | 0 | 1814 | | var statusRowsUpdated = await PersistCustomerReturnStatusAsync( |
| | 0 | 1815 | | orderIds, |
| | 0 | 1816 | | customerReturnStatus.Id, |
| | 0 | 1817 | | lastStatusChangeDate, |
| | 0 | 1818 | | cancellationToken); |
| | | 1819 | | |
| | 0 | 1820 | | if (statusRowsUpdated == 0) |
| | | 1821 | | { |
| | 0 | 1822 | | throw new InvalidOperationException( |
| | 0 | 1823 | | "Транзакция создана, но статус «Возврат покупателя» не записан в заказы"); |
| | | 1824 | | } |
| | | 1825 | | |
| | 0 | 1826 | | await _orderServices.UpdateOrders(trackedOrders); |
| | | 1827 | | |
| | 0 | 1828 | | foreach (var order in trackedOrders) |
| | | 1829 | | { |
| | 0 | 1830 | | order.AppStatus = customerReturnStatus; |
| | | 1831 | | } |
| | | 1832 | | |
| | 0 | 1833 | | await TryRecordStatusTransitionHistoryAsync( |
| | 0 | 1834 | | TransactionType.CustomerReturn, |
| | 0 | 1835 | | trackedOrders, |
| | 0 | 1836 | | fromStatusByOrderId, |
| | 0 | 1837 | | comment, |
| | 0 | 1838 | | performedAt, |
| | 0 | 1839 | | cancellationToken); |
| | | 1840 | | |
| | 0 | 1841 | | await TryRecordOneCHistoryMovementAsync( |
| | 0 | 1842 | | trackedOrders, |
| | 0 | 1843 | | transferResult, |
| | 0 | 1844 | | transactionId, |
| | 0 | 1845 | | historyWindowStart, |
| | 0 | 1846 | | senderWarehouse, |
| | 0 | 1847 | | recipient); |
| | | 1848 | | |
| | | 1849 | | // Берём первый документ для сохранения в результат каждого заказа группы |
| | 0 | 1850 | | var firstDocGuid = oneCDocumentIds.FirstOrDefault(); // GUID Ref_Key |
| | 0 | 1851 | | var firstDocNumber = oneCDocumentLabels.FirstOrDefault(); // "НФY1-001620" |
| | 0 | 1852 | | var groupIsPosted = successfulTransfers.All(tr => tr.IsPosted); |
| | 0 | 1853 | | var crPostingErrors = string.Join("; ", |
| | 0 | 1854 | | successfulTransfers |
| | 0 | 1855 | | .Where(tr => !tr.IsPosted && !string.IsNullOrWhiteSpace(tr.PostingError)) |
| | 0 | 1856 | | .Select(tr => tr.PostingError) |
| | 0 | 1857 | | .Distinct()); |
| | 0 | 1858 | | var crMissingNom = string.Join("; ", |
| | 0 | 1859 | | successfulTransfers |
| | 0 | 1860 | | .Where(tr => !string.IsNullOrWhiteSpace(tr.MissingNomenclature)) |
| | 0 | 1861 | | .Select(tr => tr.MissingNomenclature) |
| | 0 | 1862 | | .Distinct()); |
| | 0 | 1863 | | var crDraftDetail = !string.IsNullOrWhiteSpace(crPostingErrors) |
| | 0 | 1864 | | ? crPostingErrors |
| | 0 | 1865 | | : !string.IsNullOrWhiteSpace(crMissingNom) |
| | 0 | 1866 | | ? $"не найдена номенклатура: {crMissingNom}" |
| | 0 | 1867 | | : groupIsPosted ? null : "документ не проведён в 1С (черновик)"; |
| | 0 | 1868 | | if (!groupIsPosted) |
| | 0 | 1869 | | crDraftDetail = OneCResponseErrors.AppendOneCDetails(crDraftDetail, successfulTransfers.Where(tr => |
| | | 1870 | | |
| | 0 | 1871 | | foreach (var order in trackedOrders) |
| | | 1872 | | { |
| | 0 | 1873 | | processedCount++; |
| | 0 | 1874 | | await LogCustomerReturnPostedAsync( |
| | 0 | 1875 | | executionId, stepId, order, recipient, transactionId, |
| | 0 | 1876 | | firstDocGuid, firstDocNumber, groupIsPosted, crDraftDetail, cancellationToken); |
| | | 1877 | | } |
| | 0 | 1878 | | } |
| | 0 | 1879 | | catch (Exception ex) |
| | | 1880 | | { |
| | 0 | 1881 | | await SendLogAsync(jobId, $"✗ Ошибка записи транзакции после 1С (группа «{recipient}»): {ex.Message}"); |
| | 0 | 1882 | | foreach (var order in groupOrders) |
| | | 1883 | | { |
| | 0 | 1884 | | failedCount++; |
| | 0 | 1885 | | await LogCustomerReturnFailedAsync(executionId, stepId, order, recipient, |
| | 0 | 1886 | | $"1С OK, ошибка системы: {ex.Message}", documentLabel, cancellationToken); |
| | | 1887 | | } |
| | 0 | 1888 | | } |
| | 0 | 1889 | | } |
| | | 1890 | | |
| | 0 | 1891 | | return (processedCount, failedCount); |
| | 0 | 1892 | | } |
| | | 1893 | | |
| | | 1894 | | private async Task<List<OneCResponse>> PostCustomerReturnTo1CWithRetryAsync( |
| | | 1895 | | List<Order> orders, |
| | | 1896 | | string senderWarehouse, |
| | | 1897 | | string recipientWarehouse, |
| | | 1898 | | DateTime oneCOperationDate, |
| | | 1899 | | string? jobId, |
| | | 1900 | | CancellationToken cancellationToken) |
| | | 1901 | | { |
| | | 1902 | | const int maxRetries = 3; |
| | 0 | 1903 | | var retryDelay = TimeSpan.FromSeconds(5); |
| | 0 | 1904 | | Exception? lastException = null; |
| | | 1905 | | |
| | 0 | 1906 | | for (var attempt = 1; attempt <= maxRetries; attempt++) |
| | | 1907 | | { |
| | | 1908 | | try |
| | | 1909 | | { |
| | 0 | 1910 | | await SendLogAsync(jobId, |
| | 0 | 1911 | | $" 1С: перемещение {senderWarehouse} → {recipientWarehouse}, {orders.Count} заказ(ов), попытка {att |
| | 0 | 1912 | | var result = await _oneCTransferManager.TransferStockWithCustomWarehouses( |
| | 0 | 1913 | | orders, |
| | 0 | 1914 | | senderWarehouse, |
| | 0 | 1915 | | recipientWarehouse, |
| | 0 | 1916 | | TransactionType.CustomerReturn, |
| | 0 | 1917 | | oneCOperationDate, |
| | 0 | 1918 | | SystemUserName); |
| | 0 | 1919 | | return result; |
| | | 1920 | | } |
| | | 1921 | | catch (Exception ex) |
| | | 1922 | | { |
| | 0 | 1923 | | lastException = ex; |
| | 0 | 1924 | | var detail = FormatExceptionDetail(ex); |
| | 0 | 1925 | | Console.WriteLine($"[1C] CustomerReturn попытка {attempt}/{maxRetries}: {detail}"); |
| | 0 | 1926 | | await SendLogAsync(jobId, $" ✗ 1С попытка {attempt}/{maxRetries}: {detail}"); |
| | 0 | 1927 | | if (attempt < maxRetries) |
| | | 1928 | | { |
| | 0 | 1929 | | await Task.Delay(retryDelay, cancellationToken); |
| | | 1930 | | } |
| | | 1931 | | } |
| | | 1932 | | } |
| | | 1933 | | |
| | 0 | 1934 | | throw lastException ?? new Exception("1C posting failed"); |
| | 0 | 1935 | | } |
| | | 1936 | | |
| | | 1937 | | private const int TransactionResultCommentMaxLength = 1000; |
| | | 1938 | | |
| | | 1939 | | private async Task LogCustomerReturnPostedAsync( |
| | | 1940 | | long executionId, |
| | | 1941 | | long stepId, |
| | | 1942 | | Order order, |
| | | 1943 | | string recipientWarehouse, |
| | | 1944 | | int transactionId, |
| | | 1945 | | string? oneCDocumentId, // GUID Ref_Key |
| | | 1946 | | string? oneCDocumentNumber, // Читаемый номер "НФY1-001620" |
| | | 1947 | | bool isPosted, |
| | | 1948 | | string? draftReason, |
| | | 1949 | | CancellationToken cancellationToken) |
| | | 1950 | | { |
| | 0 | 1951 | | var match = await _context.BackgroundOrderMatches |
| | 0 | 1952 | | .Where(m => m.ExecutionId == executionId && m.OrderId == order.Id) |
| | 0 | 1953 | | .OrderByDescending(m => m.CreatedAt) |
| | 0 | 1954 | | .FirstOrDefaultAsync(cancellationToken); |
| | | 1955 | | |
| | 0 | 1956 | | var docLabel = oneCDocumentNumber ?? oneCDocumentId ?? "—"; |
| | 0 | 1957 | | var status = isPosted ? "PostedTo1C" : "DraftIn1C"; |
| | 0 | 1958 | | var comment = $"1С: {docLabel}" + (!isPosted && !string.IsNullOrWhiteSpace(draftReason) ? $" ({draftReason})" : |
| | | 1959 | | // Comment — varchar(1000); полный текст причины с ответом 1С лежит в ErrorMessage (text) ниже. |
| | 0 | 1960 | | if (comment.Length > TransactionResultCommentMaxLength) |
| | 0 | 1961 | | comment = comment[..(TransactionResultCommentMaxLength - 1)] + "…"; |
| | 0 | 1962 | | var resultId = await _loggingService.LogTransactionResultAsync( |
| | 0 | 1963 | | executionId, |
| | 0 | 1964 | | stepId, |
| | 0 | 1965 | | match?.Id, |
| | 0 | 1966 | | order.Id, |
| | 0 | 1967 | | recipientWarehouse, |
| | 0 | 1968 | | transactionId, |
| | 0 | 1969 | | status, |
| | 0 | 1970 | | comment, |
| | 0 | 1971 | | cancellationToken); |
| | | 1972 | | |
| | 0 | 1973 | | await _loggingService.UpdateTransactionResultAsync( |
| | 0 | 1974 | | resultId, |
| | 0 | 1975 | | oneCDocumentId: oneCDocumentId, |
| | 0 | 1976 | | oneCDocumentNumber: oneCDocumentNumber, |
| | 0 | 1977 | | isPosted: isPosted, |
| | 0 | 1978 | | errorMessage: !isPosted ? draftReason : null, |
| | 0 | 1979 | | cancellationToken: cancellationToken); |
| | 0 | 1980 | | } |
| | | 1981 | | |
| | | 1982 | | private async Task LogCustomerReturnFailedAsync( |
| | | 1983 | | long executionId, |
| | | 1984 | | long stepId, |
| | | 1985 | | Order order, |
| | | 1986 | | string? recipientWarehouse, |
| | | 1987 | | string errorMessage, |
| | | 1988 | | string? oneCDocumentLabel, |
| | | 1989 | | CancellationToken cancellationToken) |
| | | 1990 | | { |
| | 0 | 1991 | | var match = await _context.BackgroundOrderMatches |
| | 0 | 1992 | | .Where(m => m.ExecutionId == executionId && m.OrderId == order.Id) |
| | 0 | 1993 | | .OrderByDescending(m => m.CreatedAt) |
| | 0 | 1994 | | .FirstOrDefaultAsync(cancellationToken); |
| | | 1995 | | |
| | 0 | 1996 | | var resultId = await _loggingService.LogTransactionResultAsync( |
| | 0 | 1997 | | executionId, |
| | 0 | 1998 | | stepId, |
| | 0 | 1999 | | match?.Id, |
| | 0 | 2000 | | order.Id, |
| | 0 | 2001 | | recipientWarehouse, |
| | 0 | 2002 | | null, |
| | 0 | 2003 | | "Failed", |
| | 0 | 2004 | | oneCDocumentLabel, |
| | 0 | 2005 | | cancellationToken); |
| | | 2006 | | |
| | 0 | 2007 | | await _loggingService.UpdateTransactionResultAsync( |
| | 0 | 2008 | | resultId, |
| | 0 | 2009 | | status: "Failed", |
| | 0 | 2010 | | errorMessage: errorMessage.Length > 2000 ? errorMessage[..2000] : errorMessage, |
| | 0 | 2011 | | cancellationToken: cancellationToken); |
| | 0 | 2012 | | } |
| | | 2013 | | |
| | | 2014 | | internal static void ApplySystemAttribution(IEnumerable<Order> orders) |
| | | 2015 | | { |
| | 10 | 2016 | | foreach (var order in orders) |
| | | 2017 | | { |
| | 3 | 2018 | | order.UpdatedBy = SystemUserName; |
| | | 2019 | | } |
| | 2 | 2020 | | } |
| | | 2021 | | |
| | | 2022 | | internal static void ClearOrderNavigationForPersist(IEnumerable<Order> orders) |
| | | 2023 | | { |
| | 18 | 2024 | | foreach (var order in orders) |
| | | 2025 | | { |
| | | 2026 | | // Save FK IDs before nulling navigation properties — EF Core would otherwise |
| | | 2027 | | // propagate the null back to the FK columns on SaveChanges. |
| | 4 | 2028 | | var ozonClientId = order.OzonClientId; |
| | 4 | 2029 | | var supplierId = order.SupplierId; |
| | 4 | 2030 | | var shipmentWarehouseId = order.ShipmentWarehouseId; |
| | 4 | 2031 | | var manufacturerId = order.ManufacturerId; |
| | 4 | 2032 | | var appStatusId = order.AppStatusId; |
| | 4 | 2033 | | var clientStatusId = order.ClientStatusId; |
| | 4 | 2034 | | var currencyId = order.СurrencyId; |
| | 4 | 2035 | | var deliveryId = order.DeliveryId; |
| | 4 | 2036 | | var etProducerId = order.EtProducerId; |
| | 4 | 2037 | | var productInfoId = order.ProductInfoId; |
| | 4 | 2038 | | var excelFileDataId = order.ExcelFileDataId; |
| | | 2039 | | |
| | 4 | 2040 | | order.OzonClient = null; |
| | 4 | 2041 | | order.Supplier = null; |
| | 4 | 2042 | | order.Manufacturer = null; |
| | 4 | 2043 | | order.AppStatus = null; |
| | 4 | 2044 | | order.ClientStatus = null; |
| | 4 | 2045 | | order.ShipmentWarehouse = null; |
| | 4 | 2046 | | order.Delivery = null; |
| | 4 | 2047 | | order.ProductInfo = null; |
| | 4 | 2048 | | order.EtProducer = null; |
| | 4 | 2049 | | order.OrderPrice = null; |
| | 4 | 2050 | | order.ExcelFileData = null; |
| | 4 | 2051 | | order.Сurrency = null; |
| | 4 | 2052 | | order.OrderExtensions = []; |
| | | 2053 | | |
| | | 2054 | | // Restore FK IDs so EF Core does not emit NULL for these columns. |
| | 4 | 2055 | | order.OzonClientId = ozonClientId; |
| | 4 | 2056 | | order.SupplierId = supplierId; |
| | 4 | 2057 | | order.ShipmentWarehouseId = shipmentWarehouseId; |
| | 4 | 2058 | | order.ManufacturerId = manufacturerId; |
| | 4 | 2059 | | order.AppStatusId = appStatusId; |
| | 4 | 2060 | | order.ClientStatusId = clientStatusId; |
| | 4 | 2061 | | order.СurrencyId = currencyId; |
| | 4 | 2062 | | order.DeliveryId = deliveryId; |
| | 4 | 2063 | | order.EtProducerId = etProducerId; |
| | 4 | 2064 | | order.ProductInfoId = productInfoId; |
| | 4 | 2065 | | order.ExcelFileDataId = excelFileDataId; |
| | | 2066 | | } |
| | 5 | 2067 | | } |
| | | 2068 | | |
| | | 2069 | | private async Task<int> PersistCustomerReturnStatusAsync( |
| | | 2070 | | IReadOnlyCollection<int> orderIds, |
| | | 2071 | | int customerReturnStatusId, |
| | | 2072 | | DateTime lastStatusChangeDate, |
| | | 2073 | | CancellationToken cancellationToken) |
| | | 2074 | | { |
| | 0 | 2075 | | if (orderIds.Count == 0) |
| | 0 | 2076 | | return 0; |
| | | 2077 | | |
| | 0 | 2078 | | return await _context.Orders |
| | 0 | 2079 | | .Where(o => orderIds.Contains(o.Id)) |
| | 0 | 2080 | | .ExecuteUpdateAsync( |
| | 0 | 2081 | | s => s |
| | 0 | 2082 | | .SetProperty(o => o.AppStatusId, customerReturnStatusId) |
| | 0 | 2083 | | .SetProperty(o => o.LastStatusChangeDate, lastStatusChangeDate) |
| | 0 | 2084 | | .SetProperty(o => o.UpdatedBy, SystemUserName), |
| | 0 | 2085 | | cancellationToken); |
| | 0 | 2086 | | } |
| | | 2087 | | |
| | | 2088 | | /// <summary> |
| | | 2089 | | /// Запись проведения 1С в OrderHistoryOneCPostings для отображения на /Studio2/OrderHistory/GetOrderHistory. |
| | | 2090 | | /// </summary> |
| | | 2091 | | private Task TryRecordOneCHistoryMovementAsync( |
| | | 2092 | | IReadOnlyList<Order> orders, |
| | | 2093 | | IReadOnlyList<OneCResponse> transferResult, |
| | | 2094 | | int transactionId, |
| | | 2095 | | DateTime historyWindowStart, |
| | | 2096 | | string? warehouseSender = null, |
| | | 2097 | | string? warehouseRecipient = null) |
| | | 2098 | | { |
| | 0 | 2099 | | return OrderHistoryOneCPostingRecorder.TryRecordMovementAsync( |
| | 0 | 2100 | | _serviceProvider, |
| | 0 | 2101 | | orders, |
| | 0 | 2102 | | transferResult, |
| | 0 | 2103 | | SystemUserName, |
| | 0 | 2104 | | transactionId > 0 ? transactionId : null, |
| | 0 | 2105 | | historyWindowStart, |
| | 0 | 2106 | | warehouseSender, |
| | 0 | 2107 | | warehouseRecipient); |
| | | 2108 | | } |
| | | 2109 | | |
| | | 2110 | | private async Task TryRecordStatusTransitionHistoryAsync( |
| | | 2111 | | TransactionType transactionType, |
| | | 2112 | | IReadOnlyList<Order> ordersWithNewStatus, |
| | | 2113 | | IReadOnlyDictionary<int, int> orderIdToFromStatusId, |
| | | 2114 | | string? comment, |
| | | 2115 | | DateTime performedAt, |
| | | 2116 | | CancellationToken cancellationToken) |
| | | 2117 | | { |
| | 0 | 2118 | | var transitions = await _statusTransitionDataServices.GetByTransactionType(transactionType); |
| | 0 | 2119 | | if (transitions.Count == 0) |
| | | 2120 | | { |
| | 0 | 2121 | | return; |
| | | 2122 | | } |
| | | 2123 | | |
| | 0 | 2124 | | await _statusTransitionHistoryService.RecordStatusTransitionHistoryAsync( |
| | 0 | 2125 | | transactionType, |
| | 0 | 2126 | | ordersWithNewStatus, |
| | 0 | 2127 | | orderIdToFromStatusId, |
| | 0 | 2128 | | transitions, |
| | 0 | 2129 | | comment, |
| | 0 | 2130 | | performedByUserId: null, |
| | 0 | 2131 | | performedAt, |
| | 0 | 2132 | | metadata: "{\"performedBy\":\"Система\"}"); |
| | 0 | 2133 | | } |
| | | 2134 | | |
| | | 2135 | | internal static string FormatExceptionDetail(Exception ex) |
| | | 2136 | | { |
| | 3 | 2137 | | var detail = ex.ToString(); |
| | 3 | 2138 | | return detail.Length <= 3000 ? detail : detail[..3000] + "…"; |
| | | 2139 | | } |
| | | 2140 | | } |