| | | 1 | | using Microsoft.AspNetCore.Http; |
| | | 2 | | using Services.ApiServices.OzonApi; |
| | | 3 | | using Services.ApiServices.OzonApi.Filters; |
| | | 4 | | using Services.BackgroundJobsServices; |
| | | 5 | | using Services.DataServices; |
| | | 6 | | using Services.ParserServices.FileProcessing; |
| | | 7 | | using SlqStudio.Application.Services.EmailService; |
| | | 8 | | using Services.SystemMonitoringServices; |
| | | 9 | | |
| | | 10 | | namespace Services.BackgroundJobsServices; |
| | | 11 | | |
| | | 12 | | public interface IOzonReportLoaderService |
| | | 13 | | { |
| | | 14 | | Task<(byte[] fileBytes, string fileName, List<(string OrderNumber, string Article)> parsedOrders)> LoadAndParseRepor |
| | | 15 | | int ozonClientId, |
| | | 16 | | DateTime reportDownloadFrom, |
| | | 17 | | DateTime reportDownloadTo, |
| | | 18 | | IReadOnlyList<string> rowFilterDateKeys, |
| | | 19 | | long executionId, |
| | | 20 | | long stepId, |
| | | 21 | | IBackgroundJobLoggingService loggingService, |
| | | 22 | | CancellationToken cancellationToken = default); |
| | | 23 | | |
| | | 24 | | Task<(byte[] fileBytes, string fileName, List<string> shipmentNumbers)> LoadAndParseReturnsReportAsync( |
| | | 25 | | int ozonClientId, |
| | | 26 | | DateTime reportDownloadFrom, |
| | | 27 | | DateTime reportDownloadTo, |
| | | 28 | | IReadOnlyList<string> rowFilterDateKeys, |
| | | 29 | | long executionId, |
| | | 30 | | long stepId, |
| | | 31 | | IBackgroundJobLoggingService loggingService, |
| | | 32 | | CancellationToken cancellationToken = default); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | public class OzonReportLoaderService : IOzonReportLoaderService |
| | | 36 | | { |
| | | 37 | | private readonly OzonClientServices _ozonClientServices; |
| | | 38 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 39 | | private readonly IEmailService _emailService; |
| | | 40 | | private readonly IFileProcessingService _fileProcessingService; |
| | | 41 | | private readonly ISystemMonitoringSignalWriter? _signals; |
| | | 42 | | |
| | 0 | 43 | | public OzonReportLoaderService( |
| | 0 | 44 | | OzonClientServices ozonClientServices, |
| | 0 | 45 | | IHttpClientFactory httpClientFactory, |
| | 0 | 46 | | IEmailService emailService, |
| | 0 | 47 | | IFileProcessingService fileProcessingService, |
| | 0 | 48 | | ISystemMonitoringSignalWriter? signals = null) |
| | | 49 | | { |
| | 0 | 50 | | _ozonClientServices = ozonClientServices; |
| | 0 | 51 | | _httpClientFactory = httpClientFactory; |
| | 0 | 52 | | _emailService = emailService; |
| | 0 | 53 | | _fileProcessingService = fileProcessingService; |
| | 0 | 54 | | _signals = signals; |
| | 0 | 55 | | } |
| | | 56 | | |
| | | 57 | | public async Task<(byte[] fileBytes, string fileName, List<(string OrderNumber, string Article)> parsedOrders)> Load |
| | | 58 | | int ozonClientId, |
| | | 59 | | DateTime reportDownloadFrom, |
| | | 60 | | DateTime reportDownloadTo, |
| | | 61 | | IReadOnlyList<string> rowFilterDateKeys, |
| | | 62 | | long executionId, |
| | | 63 | | long stepId, |
| | | 64 | | IBackgroundJobLoggingService loggingService, |
| | | 65 | | CancellationToken cancellationToken = default) |
| | | 66 | | { |
| | 0 | 67 | | var reportLoadId = await loggingService.LogReportLoadAsync( |
| | 0 | 68 | | executionId, stepId, ozonClientId, reportDownloadFrom, reportDownloadTo, cancellationToken: cancellationToke |
| | | 69 | | |
| | | 70 | | try |
| | | 71 | | { |
| | 0 | 72 | | var ozonClient = await _ozonClientServices.GetOzonClientAsync(ozonClientId); |
| | 0 | 73 | | if (ozonClient == null || string.IsNullOrWhiteSpace(ozonClient.DecryptClientId) || string.IsNullOrWhiteSpace |
| | 0 | 74 | | throw new Exception($"Ozon client {ozonClientId} not found or has invalid credentials"); |
| | | 75 | | |
| | 0 | 76 | | var apiManager = new OzonApiDataManager(_httpClientFactory, _emailService, ozonClient.DecryptClientId, ozonC |
| | | 77 | | |
| | 0 | 78 | | var reportRequest = new PostingsReportRequest |
| | 0 | 79 | | { |
| | 0 | 80 | | Filter = new PostingsReportRequestFilter |
| | 0 | 81 | | { |
| | 0 | 82 | | ProcessedAtFrom = reportDownloadFrom, |
| | 0 | 83 | | ProcessedAtTo = reportDownloadTo, |
| | 0 | 84 | | DeliverySchema = new[] { "fbs" }, |
| | 0 | 85 | | IsExpress = false, |
| | 0 | 86 | | Sku = Array.Empty<string>(), |
| | 0 | 87 | | CancelReasonId = Array.Empty<string>(), |
| | 0 | 88 | | OfferId = string.Empty, |
| | 0 | 89 | | StatusAlias = Array.Empty<string>(), |
| | 0 | 90 | | Statuses = Array.Empty<string>(), |
| | 0 | 91 | | Title = string.Empty, |
| | 0 | 92 | | WarehouseId = Array.Empty<long>(), |
| | 0 | 93 | | DeliveryMethodId = Array.Empty<long>() |
| | 0 | 94 | | }, |
| | 0 | 95 | | Language = "DEFAULT", |
| | 0 | 96 | | With = new PostingsReportRequestWith |
| | 0 | 97 | | { |
| | 0 | 98 | | AdditionalData = false, |
| | 0 | 99 | | AnalyticsData = false, |
| | 0 | 100 | | CustomerData = false, |
| | 0 | 101 | | JewelryCodes = false |
| | 0 | 102 | | } |
| | 0 | 103 | | }; |
| | | 104 | | |
| | 0 | 105 | | Console.WriteLine( |
| | 0 | 106 | | $"[OzonReportLoader] Requesting report for API period {reportDownloadFrom:O} - {reportDownloadTo:O}, row |
| | 0 | 107 | | var reportCode = await apiManager.GetReportCode(reportRequest); |
| | 0 | 108 | | await loggingService.UpdateReportLoadAsync(reportLoadId, status: "Requested", cancellationToken: cancellatio |
| | | 109 | | |
| | 0 | 110 | | Console.WriteLine($"[OzonReportLoader] Report code: {reportCode}, waiting for ready..."); |
| | 0 | 111 | | var fileUrl = await apiManager.WaitForReportReady(reportCode); |
| | 0 | 112 | | await loggingService.UpdateReportLoadAsync(reportLoadId, fileUrl: fileUrl, status: "Ready", cancellationToke |
| | | 113 | | |
| | 0 | 114 | | Console.WriteLine($"[OzonReportLoader] Downloading report from: {fileUrl}"); |
| | 0 | 115 | | var fileBytes = await DownloadReportBytesAsync(fileUrl, cancellationToken); |
| | 0 | 116 | | var fileName = BuildReportFileName(reportCode); |
| | | 117 | | |
| | 0 | 118 | | await loggingService.UpdateReportLoadAsync(reportLoadId, fileName: fileName, fileSizeBytes: fileBytes.Length |
| | | 119 | | |
| | 0 | 120 | | Console.WriteLine($"[OzonReportLoader] Parsing CSV file, size: {fileBytes.Length} bytes"); |
| | 0 | 121 | | await using var stream = new MemoryStream(fileBytes); |
| | 0 | 122 | | var reportFile = new FormFile(stream, 0, fileBytes.Length, "excelFile", fileName) |
| | 0 | 123 | | { |
| | 0 | 124 | | Headers = new HeaderDictionary(), |
| | 0 | 125 | | ContentType = "text/csv" |
| | 0 | 126 | | }; |
| | | 127 | | |
| | 0 | 128 | | var parsedOrders = await _fileProcessingService.ProcessFileAsync( |
| | 0 | 129 | | reportFile, |
| | 0 | 130 | | dateColumnName: ReportDeliveryDateFilter.DeliveryDateColumnName, |
| | 0 | 131 | | selectedDateValues: rowFilterDateKeys); |
| | | 132 | | |
| | 0 | 133 | | var uniqueOrderNumbers = parsedOrders.Select(o => o.OrderNumber).Distinct().Count(); |
| | 0 | 134 | | await loggingService.UpdateReportLoadAsync( |
| | 0 | 135 | | reportLoadId, |
| | 0 | 136 | | totalRows: parsedOrders.Count, |
| | 0 | 137 | | rowsWithRequiredData: parsedOrders.Count, |
| | 0 | 138 | | uniqueOrderNumbers: uniqueOrderNumbers, |
| | 0 | 139 | | cancellationToken: cancellationToken); |
| | | 140 | | |
| | 0 | 141 | | Console.WriteLine( |
| | 0 | 142 | | $"[OzonReportLoader] Success: {parsedOrders.Count} rows after filter [{string.Join(", ", rowFilterDateKe |
| | | 143 | | |
| | 0 | 144 | | await (_signals?.RecordAsync("ozon-report-import", "success", cancellationToken: cancellationToken) ?? Task. |
| | 0 | 145 | | return (fileBytes, fileName, parsedOrders); |
| | 0 | 146 | | } |
| | 0 | 147 | | catch (Exception ex) |
| | | 148 | | { |
| | 0 | 149 | | await loggingService.UpdateReportLoadAsync(reportLoadId, status: "Failed", errorMessage: ex.Message, cancell |
| | 0 | 150 | | await (_signals?.RecordAsync("ozon-report-import", "failure", message: "Ошибка загрузки отчёта Ozon", cancel |
| | 0 | 151 | | throw; |
| | | 152 | | } |
| | 0 | 153 | | } |
| | | 154 | | |
| | | 155 | | public async Task<(byte[] fileBytes, string fileName, List<string> shipmentNumbers)> LoadAndParseReturnsReportAsync( |
| | | 156 | | int ozonClientId, |
| | | 157 | | DateTime reportDownloadFrom, |
| | | 158 | | DateTime reportDownloadTo, |
| | | 159 | | IReadOnlyList<string> rowFilterDateKeys, |
| | | 160 | | long executionId, |
| | | 161 | | long stepId, |
| | | 162 | | IBackgroundJobLoggingService loggingService, |
| | | 163 | | CancellationToken cancellationToken = default) |
| | | 164 | | { |
| | 0 | 165 | | var reportLoadId = await loggingService.LogReportLoadAsync( |
| | 0 | 166 | | executionId, stepId, ozonClientId, reportDownloadFrom, reportDownloadTo, cancellationToken: cancellationToke |
| | | 167 | | |
| | | 168 | | try |
| | | 169 | | { |
| | 0 | 170 | | var ozonClient = await _ozonClientServices.GetOzonClientAsync(ozonClientId); |
| | 0 | 171 | | if (ozonClient == null || string.IsNullOrWhiteSpace(ozonClient.DecryptClientId) || string.IsNullOrWhiteSpace |
| | 0 | 172 | | throw new Exception($"Ozon client {ozonClientId} not found or has invalid credentials"); |
| | | 173 | | |
| | 0 | 174 | | var apiManager = new OzonApiDataManager(_httpClientFactory, _emailService, ozonClient.DecryptClientId, ozonC |
| | | 175 | | |
| | 0 | 176 | | var reportFromUtc = TimeZoneInfo.ConvertTimeToUtc( |
| | 0 | 177 | | DateTime.SpecifyKind(reportDownloadFrom.Date, DateTimeKind.Unspecified), |
| | 0 | 178 | | ReportDeliveryDateFilter.MoscowTimeZone); |
| | 0 | 179 | | var reportToUtc = TimeZoneInfo.ConvertTimeToUtc( |
| | 0 | 180 | | DateTime.SpecifyKind(reportDownloadTo, DateTimeKind.Unspecified), |
| | 0 | 181 | | ReportDeliveryDateFilter.MoscowTimeZone); |
| | 0 | 182 | | var reportCode = await apiManager.CreateSellerReturnsReportAsync(reportFromUtc, reportToUtc); |
| | 0 | 183 | | await loggingService.UpdateReportLoadAsync(reportLoadId, status: "Requested", cancellationToken: cancellatio |
| | | 184 | | |
| | 0 | 185 | | var fileUrl = await apiManager.WaitForReportReady(reportCode); |
| | 0 | 186 | | await loggingService.UpdateReportLoadAsync(reportLoadId, fileUrl: fileUrl, status: "Ready", cancellationToke |
| | | 187 | | |
| | 0 | 188 | | var fileBytes = await DownloadReportBytesAsync(fileUrl, cancellationToken); |
| | 0 | 189 | | var fileName = BuildReturnsReportFileName(reportCode, fileUrl); |
| | 0 | 190 | | var contentType = GuessContentType(fileName); |
| | | 191 | | |
| | 0 | 192 | | await loggingService.UpdateReportLoadAsync(reportLoadId, fileName: fileName, fileSizeBytes: fileBytes.Length |
| | | 193 | | |
| | 0 | 194 | | await using var stream = new MemoryStream(fileBytes); |
| | 0 | 195 | | var reportFile = new FormFile(stream, 0, fileBytes.Length, "excelFile", fileName) |
| | 0 | 196 | | { |
| | 0 | 197 | | Headers = new HeaderDictionary(), |
| | 0 | 198 | | ContentType = contentType |
| | 0 | 199 | | }; |
| | | 200 | | |
| | 0 | 201 | | var shipmentNumbers = await _fileProcessingService.ProcessShipmentOnlyAsync( |
| | 0 | 202 | | reportFile, |
| | 0 | 203 | | dateColumnName: ReportDeliveryDateFilter.ReturnsStatusDateColumnName, |
| | 0 | 204 | | selectedDateValues: rowFilterDateKeys); |
| | | 205 | | |
| | 0 | 206 | | Console.WriteLine( |
| | 0 | 207 | | $"[OzonReportLoader] Returns: {shipmentNumbers.Count} rows after filter [{string.Join(", ", rowFilterDat |
| | | 208 | | |
| | 0 | 209 | | var uniqueShipments = shipmentNumbers |
| | 0 | 210 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 0 | 211 | | .Select(x => x.Trim()) |
| | 0 | 212 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 213 | | .ToList(); |
| | | 214 | | |
| | 0 | 215 | | await loggingService.UpdateReportLoadAsync( |
| | 0 | 216 | | reportLoadId, |
| | 0 | 217 | | totalRows: shipmentNumbers.Count, |
| | 0 | 218 | | rowsWithRequiredData: shipmentNumbers.Count, |
| | 0 | 219 | | uniqueOrderNumbers: uniqueShipments.Count, |
| | 0 | 220 | | cancellationToken: cancellationToken); |
| | | 221 | | |
| | 0 | 222 | | await (_signals?.RecordAsync("ozon-report-import", "success", cancellationToken: cancellationToken) ?? Task. |
| | 0 | 223 | | return (fileBytes, fileName, uniqueShipments); |
| | 0 | 224 | | } |
| | 0 | 225 | | catch (Exception ex) |
| | | 226 | | { |
| | 0 | 227 | | await loggingService.UpdateReportLoadAsync(reportLoadId, status: "Failed", errorMessage: ex.Message, cancell |
| | 0 | 228 | | await (_signals?.RecordAsync("ozon-report-import", "failure", message: "Ошибка загрузки отчёта Ozon", cancel |
| | 0 | 229 | | throw; |
| | | 230 | | } |
| | 0 | 231 | | } |
| | | 232 | | |
| | | 233 | | private async Task<byte[]> DownloadReportBytesAsync(string fileUrl, CancellationToken cancellationToken = default) |
| | | 234 | | { |
| | 0 | 235 | | using var client = _httpClientFactory.CreateClient(); |
| | 0 | 236 | | return await OzonReportDownloadHelper.DownloadBytesWithRetryAsync(client, fileUrl, cancellationToken: cancellati |
| | 0 | 237 | | } |
| | | 238 | | |
| | | 239 | | private static string BuildReportFileName(string reportCode) |
| | | 240 | | { |
| | 0 | 241 | | return $"ozon_report_{reportCode}_{DateTime.UtcNow:yyyyMMdd_HHmmss}.csv"; |
| | | 242 | | } |
| | | 243 | | |
| | | 244 | | private static string BuildReturnsReportFileName(string reportCode, string? fileUrl) |
| | | 245 | | { |
| | 0 | 246 | | var extension = ".xlsx"; |
| | 0 | 247 | | if (!string.IsNullOrWhiteSpace(fileUrl)) |
| | | 248 | | { |
| | | 249 | | try |
| | | 250 | | { |
| | 0 | 251 | | extension = Path.GetExtension(new Uri(fileUrl).AbsolutePath); |
| | 0 | 252 | | } |
| | 0 | 253 | | catch |
| | | 254 | | { |
| | 0 | 255 | | extension = ".xlsx"; |
| | 0 | 256 | | } |
| | | 257 | | } |
| | | 258 | | |
| | 0 | 259 | | if (string.IsNullOrWhiteSpace(extension)) |
| | 0 | 260 | | extension = ".xlsx"; |
| | | 261 | | |
| | 0 | 262 | | return $"ozon_returns_{reportCode}_{DateTime.UtcNow:yyyyMMdd_HHmmss}{extension}"; |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | private static string GuessContentType(string fileName) |
| | | 266 | | { |
| | 0 | 267 | | var extension = Path.GetExtension(fileName)?.ToLowerInvariant(); |
| | 0 | 268 | | return extension switch |
| | 0 | 269 | | { |
| | 0 | 270 | | ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
| | 0 | 271 | | ".xls" => "application/vnd.ms-excel", |
| | 0 | 272 | | _ => "text/csv" |
| | 0 | 273 | | }; |
| | | 274 | | } |
| | | 275 | | } |