| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using OzonDomains.Models; |
| | | 5 | | using Services.BitrixStockServices; |
| | | 6 | | using Services.DataServices; |
| | | 7 | | using Services.ParserServices.FielParsers; |
| | | 8 | | using SlqStudio.Application.Services.EmailService; |
| | | 9 | | |
| | | 10 | | namespace Services.ChannelTaskServices; |
| | | 11 | | |
| | 39 | 12 | | public sealed class ChannelTaskExecutor( |
| | 39 | 13 | | IServiceScopeFactory scopeFactory, |
| | 39 | 14 | | ILogger<ChannelTaskExecutor> logger) |
| | | 15 | | { |
| | 39 | 16 | | private readonly ILogger<ChannelTaskExecutor> _logger = logger; |
| | | 17 | | private const string BitrixEmailRecipient = "lex@interparts.ru"; |
| | 1 | 18 | | private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true }; |
| | | 19 | | |
| | | 20 | | public async Task ExecuteAsync( |
| | | 21 | | string taskId, |
| | | 22 | | ChannelTaskType type, |
| | | 23 | | string payloadJson, |
| | | 24 | | Action<string, Action<ChannelTaskState>> update, |
| | | 25 | | Action<string, string> registerFile, |
| | | 26 | | CancellationToken ct) |
| | | 27 | | { |
| | 23 | 28 | | _logger.LogDebug("Channel task {TaskId} started ({Type})", taskId, type); |
| | | 29 | | switch (type) |
| | | 30 | | { |
| | | 31 | | case ChannelTaskType.BitrixSyncReportExcel: |
| | 11 | 32 | | await ExecuteBitrixExcelAsync(taskId, payloadJson, sendEmail: false, update, registerFile, ct); |
| | 2 | 33 | | break; |
| | | 34 | | case ChannelTaskType.BitrixSyncReportEmail: |
| | 2 | 35 | | await ExecuteBitrixExcelAsync(taskId, payloadJson, sendEmail: true, update, registerFile, ct); |
| | 1 | 36 | | break; |
| | | 37 | | case ChannelTaskType.TransactionExcel: |
| | 9 | 38 | | await ExecuteTransactionExcelAsync(taskId, payloadJson, update, registerFile, ct); |
| | 2 | 39 | | break; |
| | | 40 | | default: |
| | 1 | 41 | | Fail(taskId, update, $"Неизвестный тип задачи: {type}"); |
| | | 42 | | break; |
| | | 43 | | } |
| | 6 | 44 | | } |
| | | 45 | | |
| | | 46 | | private async Task ExecuteBitrixExcelAsync( |
| | | 47 | | string taskId, |
| | | 48 | | string payloadJson, |
| | | 49 | | bool sendEmail, |
| | | 50 | | Action<string, Action<ChannelTaskState>> update, |
| | | 51 | | Action<string, string> registerFile, |
| | | 52 | | CancellationToken ct) |
| | | 53 | | { |
| | 13 | 54 | | var payload = JsonSerializer.Deserialize<BitrixSyncReportTaskPayload>(payloadJson, JsonOptions) |
| | 13 | 55 | | ?? throw new InvalidOperationException("Некорректный payload Bitrix."); |
| | | 56 | | |
| | 9 | 57 | | if (string.IsNullOrWhiteSpace(payload.ReportId)) |
| | 4 | 58 | | throw new InvalidOperationException("reportId обязателен."); |
| | | 59 | | |
| | 5 | 60 | | using var scope = scopeFactory.CreateScope(); |
| | 5 | 61 | | var reportService = scope.ServiceProvider.GetRequiredService<IBitrixStockSyncReportService>(); |
| | 5 | 62 | | IEmailService? emailService = sendEmail |
| | 5 | 63 | | ? scope.ServiceProvider.GetRequiredService<IEmailService>() |
| | 5 | 64 | | : null; |
| | | 65 | | |
| | 5 | 66 | | SetStage(taskId, update, ChannelTaskStages.Loading, "Загрузка данных отчёта", 5); |
| | 8 | 67 | | update(taskId, s => s.ReportId = payload.ReportId); |
| | | 68 | | |
| | 5 | 69 | | var progress = new Action<BitrixStockExcelBuildProgress>(p => |
| | 5 | 70 | | { |
| | 25 | 71 | | update(taskId, s => |
| | 25 | 72 | | { |
| | 18 | 73 | | s.Stage = p.Stage; |
| | 18 | 74 | | s.Status = p.Stage; |
| | 18 | 75 | | s.Current = p.Current; |
| | 18 | 76 | | s.Total = p.Total; |
| | 18 | 77 | | s.Percent = p.Percent; |
| | 18 | 78 | | if (!string.IsNullOrWhiteSpace(p.Message)) |
| | 18 | 79 | | s.Message = p.Message; |
| | 43 | 80 | | }); |
| | 30 | 81 | | }); |
| | | 82 | | |
| | 5 | 83 | | var (bytes, filename) = await BitrixStockSyncReportExcelBuilder.BuildAsync( |
| | 5 | 84 | | reportService, |
| | 5 | 85 | | payload.ReportId.Trim(), |
| | 5 | 86 | | payload.Query ?? new BitrixStockSyncReportQuery(), |
| | 5 | 87 | | progress, |
| | 5 | 88 | | ct); |
| | | 89 | | |
| | 5 | 90 | | if (bytes == null || bytes.Length == 0) |
| | 1 | 91 | | throw new InvalidOperationException("Отчёт не найден или Excel-пустой."); |
| | | 92 | | |
| | 4 | 93 | | SetStage(taskId, update, ChannelTaskStages.Saving, "Сохранение файла", 95); |
| | 4 | 94 | | var safeName = string.IsNullOrWhiteSpace(filename) ? $"sync-{taskId}.xlsx" : filename; |
| | 4 | 95 | | var fullPath = await SaveFileAsync(taskId, safeName, bytes, ct); |
| | | 96 | | |
| | 4 | 97 | | if (sendEmail) |
| | | 98 | | { |
| | 2 | 99 | | SetStage(taskId, update, ChannelTaskStages.Sending, "Отправка на почту…", 98); |
| | 2 | 100 | | var subject = $"Отчёт синхронизации остатков {BitrixStockMskDateTime.FormatNow()}"; |
| | 2 | 101 | | var body = $"Отчёт синхронизации остатков Ozon во вложении.\nID отчёта: {payload.ReportId}"; |
| | 2 | 102 | | var sent = await emailService!.SendEmailWithAttachmentAsync( |
| | 2 | 103 | | BitrixEmailRecipient, |
| | 2 | 104 | | subject, |
| | 2 | 105 | | body, |
| | 2 | 106 | | bytes, |
| | 2 | 107 | | safeName, |
| | 2 | 108 | | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); |
| | | 109 | | |
| | 2 | 110 | | if (!sent) |
| | 1 | 111 | | throw new InvalidOperationException("Не удалось отправить письмо"); |
| | | 112 | | |
| | 1 | 113 | | Complete(taskId, update, registerFile, ChannelTaskResultKind.Email, safeName, "Письмо отправлено на lex@inte |
| | 1 | 114 | | return; |
| | | 115 | | } |
| | | 116 | | |
| | 2 | 117 | | Complete(taskId, update, registerFile, ChannelTaskResultKind.File, safeName, "Файл готов к скачиванию", fullPath |
| | 3 | 118 | | } |
| | | 119 | | |
| | | 120 | | private async Task ExecuteTransactionExcelAsync( |
| | | 121 | | string taskId, |
| | | 122 | | string payloadJson, |
| | | 123 | | Action<string, Action<ChannelTaskState>> update, |
| | | 124 | | Action<string, string> registerFile, |
| | | 125 | | CancellationToken ct) |
| | | 126 | | { |
| | 9 | 127 | | var payload = JsonSerializer.Deserialize<TransactionExcelTaskPayload>(payloadJson, JsonOptions) |
| | 9 | 128 | | ?? throw new InvalidOperationException("Некорректный payload Transaction."); |
| | | 129 | | |
| | 9 | 130 | | using var scope = scopeFactory.CreateScope(); |
| | 9 | 131 | | var orderServices = scope.ServiceProvider.GetRequiredService<OrdersDataServices>(); |
| | 9 | 132 | | var transactionDataServices = scope.ServiceProvider.GetRequiredService<TransactionDataServices>(); |
| | 9 | 133 | | var excelExporter = scope.ServiceProvider.GetRequiredService<ExcelExporter>(); |
| | | 134 | | |
| | 9 | 135 | | SetStage(taskId, update, ChannelTaskStages.Loading, "Загрузка заказов…", 10); |
| | | 136 | | |
| | | 137 | | List<Order> orders; |
| | | 138 | | string fileName; |
| | | 139 | | |
| | 9 | 140 | | if (payload.TableMode) |
| | | 141 | | { |
| | 4 | 142 | | var deleted = payload.DeletedOrderIds.ToHashSet(); |
| | 10 | 143 | | var ids = payload.OrderIds.Where(id => !deleted.Contains(id)).Distinct().ToArray(); |
| | 4 | 144 | | if (ids.Length == 0) |
| | 2 | 145 | | throw new InvalidOperationException("Нет заказов для экспорта"); |
| | | 146 | | |
| | 2 | 147 | | orders = new List<Order>(); |
| | 10 | 148 | | foreach (var orderId in ids) |
| | | 149 | | { |
| | 3 | 150 | | ct.ThrowIfCancellationRequested(); |
| | 3 | 151 | | var order = await orderServices.GetAsyncNoTracking(orderId); |
| | 3 | 152 | | if (order != null) |
| | 2 | 153 | | orders.Add(order); |
| | | 154 | | } |
| | | 155 | | |
| | 2 | 156 | | if (orders.Count == 0) |
| | 1 | 157 | | throw new InvalidOperationException("Заказы не найдены"); |
| | | 158 | | |
| | 1 | 159 | | orders = orders |
| | 2 | 160 | | .OrderBy(o => o.EtProducer?.Name ?? "") |
| | 2 | 161 | | .ThenBy(o => o.Article ?? "") |
| | 1 | 162 | | .ToList(); |
| | | 163 | | |
| | 1 | 164 | | fileName = $"Таблица_заказов_{DateTime.Now:dd.MM.yyyy_HHmmss}.xlsx"; |
| | | 165 | | } |
| | | 166 | | else |
| | | 167 | | { |
| | 5 | 168 | | if (payload.TransactionId is not > 0) |
| | 3 | 169 | | throw new InvalidOperationException("transactionId обязателен"); |
| | | 170 | | |
| | 2 | 171 | | var transaction = await transactionDataServices.GetTransaction(payload.TransactionId.Value); |
| | 2 | 172 | | if (transaction?.Orders == null || transaction.Orders.Count == 0) |
| | 1 | 173 | | throw new InvalidOperationException("Транзакция не найдена или без заказов"); |
| | | 174 | | |
| | 1 | 175 | | orders = transaction.Orders.ToList(); |
| | 1 | 176 | | fileName = $"Transaction_{transaction.CreateBy}_{transaction.CreatedDateTime:dd.MM.yyyy}.xlsx"; |
| | | 177 | | } |
| | | 178 | | |
| | 2 | 179 | | SetStage(taskId, update, ChannelTaskStages.Building, "Сборка Excel…", 60, orders.Count, orders.Count); |
| | | 180 | | |
| | | 181 | | byte[] bytes; |
| | 2 | 182 | | if (payload.TableMode) |
| | | 183 | | { |
| | 1 | 184 | | var columns = new List<string> |
| | 1 | 185 | | { |
| | 1 | 186 | | "Номер заказа", "Клиент", "Наименование товара", "Артикул", |
| | 1 | 187 | | "Производитель", "Количество", "Сумма отправления" |
| | 1 | 188 | | }; |
| | 1 | 189 | | bytes = excelExporter.ExportToExcel(orders, columns); |
| | | 190 | | } |
| | | 191 | | else |
| | | 192 | | { |
| | 1 | 193 | | bytes = excelExporter.ExportToExcel(orders); |
| | | 194 | | } |
| | | 195 | | |
| | 2 | 196 | | SetStage(taskId, update, ChannelTaskStages.Saving, "Сохранение файла", 95); |
| | 2 | 197 | | var fullPath = await SaveFileAsync(taskId, fileName, bytes, ct); |
| | 2 | 198 | | Complete(taskId, update, registerFile, ChannelTaskResultKind.File, fileName, "Файл готов к скачиванию", fullPath |
| | 2 | 199 | | } |
| | | 200 | | |
| | | 201 | | private static async Task<string> SaveFileAsync(string taskId, string fileName, byte[] bytes, CancellationToken ct) |
| | | 202 | | { |
| | 6 | 203 | | var dir = ChannelTaskProcessor.ExportDirectory; |
| | 6 | 204 | | Directory.CreateDirectory(dir); |
| | 6 | 205 | | var fullPath = Path.Combine(dir, $"{taskId}-{fileName}"); |
| | 6 | 206 | | await File.WriteAllBytesAsync(fullPath, bytes, ct); |
| | 6 | 207 | | return fullPath; |
| | 6 | 208 | | } |
| | | 209 | | |
| | | 210 | | private static void SetStage( |
| | | 211 | | string taskId, |
| | | 212 | | Action<string, Action<ChannelTaskState>> update, |
| | | 213 | | string stage, |
| | | 214 | | string message, |
| | | 215 | | int percent, |
| | | 216 | | int current = 0, |
| | | 217 | | int total = 0) |
| | | 218 | | { |
| | 24 | 219 | | update(taskId, s => |
| | 24 | 220 | | { |
| | 13 | 221 | | s.Status = stage; |
| | 13 | 222 | | s.Stage = stage; |
| | 13 | 223 | | s.Message = message; |
| | 13 | 224 | | s.Percent = percent; |
| | 13 | 225 | | s.Current = current; |
| | 13 | 226 | | s.Total = total; |
| | 13 | 227 | | s.StartedAtUtc ??= DateTime.UtcNow; |
| | 37 | 228 | | }); |
| | 24 | 229 | | } |
| | | 230 | | |
| | | 231 | | private static void Complete( |
| | | 232 | | string taskId, |
| | | 233 | | Action<string, Action<ChannelTaskState>> update, |
| | | 234 | | Action<string, string> registerFile, |
| | | 235 | | ChannelTaskResultKind resultKind, |
| | | 236 | | string fileName, |
| | | 237 | | string message, |
| | | 238 | | string? filePath = null) |
| | | 239 | | { |
| | 5 | 240 | | update(taskId, s => |
| | 5 | 241 | | { |
| | 5 | 242 | | s.Status = ChannelTaskStages.Completed; |
| | 5 | 243 | | s.Stage = ChannelTaskStages.Completed; |
| | 5 | 244 | | s.Message = message; |
| | 5 | 245 | | s.Percent = 100; |
| | 5 | 246 | | s.FileName = fileName; |
| | 5 | 247 | | s.ResultKind = resultKind; |
| | 5 | 248 | | s.CompletedAtUtc = DateTime.UtcNow; |
| | 10 | 249 | | }); |
| | | 250 | | |
| | 5 | 251 | | if (!string.IsNullOrWhiteSpace(filePath)) |
| | 4 | 252 | | registerFile(taskId, filePath); |
| | 5 | 253 | | } |
| | | 254 | | |
| | | 255 | | private static void Fail(string taskId, Action<string, Action<ChannelTaskState>> update, string error) |
| | | 256 | | { |
| | 1 | 257 | | update(taskId, s => |
| | 1 | 258 | | { |
| | 1 | 259 | | s.Status = ChannelTaskStages.Failed; |
| | 1 | 260 | | s.Stage = ChannelTaskStages.Failed; |
| | 1 | 261 | | s.Error = error; |
| | 1 | 262 | | s.Message = error; |
| | 1 | 263 | | s.CompletedAtUtc = DateTime.UtcNow; |
| | 2 | 264 | | }); |
| | 1 | 265 | | } |
| | | 266 | | } |