| | | 1 | | #pragma warning disable CS8600, CS8602, CS8603, CS8604, CS8601, CS8619, CS8629 |
| | | 2 | | using System.Diagnostics.CodeAnalysis; |
| | | 3 | | using System.Net.Http; |
| | | 4 | | using Microsoft.Extensions.Configuration; |
| | | 5 | | using Newtonsoft.Json.Linq; |
| | | 6 | | using OzonDomains; |
| | | 7 | | using OzonDomains.Models; |
| | | 8 | | using OzonRepositories.Context; |
| | | 9 | | using Services.DataServices; |
| | | 10 | | using Services.ParserServices.HelpDictEnum; |
| | | 11 | | using Services.ReleasServices.ReleaseManager; |
| | | 12 | | using System.Globalization; |
| | | 13 | | using System.Text.RegularExpressions; |
| | | 14 | | using Microsoft.Extensions.Caching.Memory; |
| | | 15 | | using Services.CacheServices.Cache; |
| | | 16 | | using SlqStudio.Application.Services.EmailService; |
| | | 17 | | using SlqStudio.Application.Services.EmailService.Implementation; |
| | | 18 | | using Microsoft.EntityFrameworkCore; |
| | | 19 | | using MySqlConnector; |
| | | 20 | | |
| | | 21 | | |
| | | 22 | | namespace Services.ParserServices |
| | | 23 | | |
| | | 24 | | { |
| | | 25 | | public class OrderCaster |
| | | 26 | | |
| | | 27 | | { |
| | | 28 | | // Кампании Яндекса, чьё имя (campaign.domain) не совпадает с названием склада |
| | | 29 | | // отгрузки в Studio2: имя кампании становится доставкой, склад берём отсюда. |
| | 0 | 30 | | private static readonly Dictionary<string, string> YandexCampaignWarehouses = new(StringComparer.Ordinal) |
| | 0 | 31 | | { |
| | 0 | 32 | | ["Interparts 2.0 V11"] = "V11", |
| | 0 | 33 | | ["Interparts 2.0 M1"] = "M1" |
| | 0 | 34 | | }; |
| | | 35 | | |
| | | 36 | | private const string YandexDeliveryProviderName = "Яндекс Маркет"; |
| | | 37 | | |
| | | 38 | | private readonly ApplicationDbContext _context; |
| | | 39 | | |
| | | 40 | | private readonly ReleaseManager _releaseManager; |
| | | 41 | | |
| | | 42 | | private readonly OrdersFileMetadataDataService _ordersFileMetadataDataService; |
| | | 43 | | |
| | | 44 | | private readonly EtProducerDataServices _etProducerDataServices; |
| | | 45 | | |
| | | 46 | | private readonly AppCache _appCache; |
| | | 47 | | |
| | | 48 | | private readonly IEmailService _emailService; |
| | | 49 | | |
| | | 50 | | private readonly DeliveryDataServices _deliveryService; |
| | | 51 | | |
| | | 52 | | private readonly OrdersDataServices _ordersDataServices; |
| | | 53 | | |
| | | 54 | | private readonly string? _imageBaseUrl; |
| | | 55 | | |
| | | 56 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 57 | | |
| | | 58 | | |
| | 0 | 59 | | public OrderCaster(ApplicationDbContext context, |
| | 0 | 60 | | ReleaseManager releaseManager, |
| | 0 | 61 | | OrdersFileMetadataDataService ordersFileMetadataDataService, |
| | 0 | 62 | | EtProducerDataServices etProducerDataServices, |
| | 0 | 63 | | AppCache appCache, |
| | 0 | 64 | | IEmailService emailService, |
| | 0 | 65 | | DeliveryDataServices deliveryService, |
| | 0 | 66 | | OrdersDataServices ordersDataServices, |
| | 0 | 67 | | IConfiguration configuration, |
| | 0 | 68 | | IHttpClientFactory httpClientFactory) |
| | | 69 | | |
| | | 70 | | { |
| | 0 | 71 | | _context = context; |
| | | 72 | | |
| | 0 | 73 | | _releaseManager = releaseManager; |
| | | 74 | | |
| | 0 | 75 | | _ordersFileMetadataDataService = ordersFileMetadataDataService; |
| | | 76 | | |
| | 0 | 77 | | _etProducerDataServices = etProducerDataServices; |
| | | 78 | | |
| | 0 | 79 | | _appCache = appCache; |
| | | 80 | | |
| | 0 | 81 | | _emailService = emailService; |
| | | 82 | | |
| | 0 | 83 | | _deliveryService = deliveryService; |
| | | 84 | | |
| | 0 | 85 | | _ordersDataServices = ordersDataServices; |
| | | 86 | | |
| | 0 | 87 | | _imageBaseUrl = configuration["ImageStorage:BaseUrl"]; |
| | | 88 | | |
| | 0 | 89 | | _httpClientFactory = httpClientFactory; |
| | 0 | 90 | | } |
| | | 91 | | |
| | | 92 | | |
| | | 93 | | public async Task<List<Order>> JsonToOrders(JArray orders) |
| | | 94 | | |
| | | 95 | | { |
| | 0 | 96 | | List<Order> resultOrders = new List<Order>(); |
| | | 97 | | |
| | | 98 | | const int maxAttempts = 3; |
| | | 99 | | |
| | 0 | 100 | | foreach (var order in orders) |
| | | 101 | | |
| | | 102 | | { |
| | 0 | 103 | | for (var attempt = 1; attempt <= maxAttempts; attempt++) |
| | | 104 | | { |
| | | 105 | | try |
| | | 106 | | |
| | | 107 | | { |
| | 0 | 108 | | resultOrders.Add(await CastToModel(order)); |
| | 0 | 109 | | break; |
| | | 110 | | } |
| | | 111 | | |
| | | 112 | | catch (Exception e) |
| | | 113 | | { |
| | | 114 | | // Неудачный SaveChanges оставляет сущности в состоянии Added в трекере — |
| | | 115 | | // без отсоединения повторная попытка вставила бы их ещё раз. |
| | 0 | 116 | | DetachAddedEntries(); |
| | | 117 | | |
| | 0 | 118 | | var shipNum = order?["Номер отправления"]?.ToString() ?? "?"; |
| | 0 | 119 | | var art = order?["Артикул"]?.ToString() ?? "?"; |
| | | 120 | | |
| | 0 | 121 | | if (IsMariaDbReturningBatchError(e)) |
| | | 122 | | { |
| | 0 | 123 | | if (attempt < maxAttempts) |
| | | 124 | | { |
| | 0 | 125 | | await Task.Delay(TimeSpan.FromMilliseconds(300 * attempt)); |
| | 0 | 126 | | continue; |
| | | 127 | | } |
| | | 128 | | |
| | | 129 | | // Известный сбой MariaDB "syntax error near RETURNING" (батчинг INSERT): |
| | | 130 | | // письмо не шлём, чтобы не спамить почту — только лог. |
| | 0 | 131 | | Console.WriteLine( |
| | 0 | 132 | | $"[OrderCaster] Заказ {shipNum} (артикул {art}) пропущен после {maxAttempts} попыток: Ma |
| | 0 | 133 | | break; |
| | | 134 | | } |
| | | 135 | | |
| | 0 | 136 | | var subject = $"[OrderCaster] Ошибка при обработке заказа {shipNum} (артикул {art}): {e.Message} |
| | 0 | 137 | | await _emailService.SendEmailAsync(subject, e.ToString()); |
| | 0 | 138 | | break; |
| | | 139 | | } |
| | | 140 | | } |
| | 0 | 141 | | } |
| | | 142 | | |
| | | 143 | | |
| | 0 | 144 | | return resultOrders; |
| | 0 | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary> |
| | | 148 | | /// Отсоединяет от трекера все сущности в состоянии Added — откат незасейвленных |
| | | 149 | | /// вставок после неудачного SaveChanges. Уже сохранённые сущности (Unchanged) не трогает. |
| | | 150 | | /// </summary> |
| | | 151 | | private void DetachAddedEntries() |
| | | 152 | | { |
| | 0 | 153 | | foreach (var entry in _context.ChangeTracker.Entries() |
| | 0 | 154 | | .Where(en => en.State == EntityState.Added).ToList()) |
| | | 155 | | { |
| | 0 | 156 | | entry.State = EntityState.Detached; |
| | | 157 | | } |
| | 0 | 158 | | } |
| | | 159 | | |
| | | 160 | | /// <summary> |
| | | 161 | | /// Известная ошибка MariaDB: "You have an error in your SQL syntax ... near 'RETURNING ...'" |
| | | 162 | | /// при склейке нескольких INSERT c RETURNING в один пакет. Транзиентная — лечится повтором. |
| | | 163 | | /// </summary> |
| | | 164 | | private static bool IsMariaDbReturningBatchError(Exception exception) |
| | | 165 | | { |
| | 0 | 166 | | for (Exception? ex = exception; ex != null; ex = ex.InnerException) |
| | | 167 | | { |
| | 0 | 168 | | if (ex is MySqlException && ex.Message.Contains("RETURNING")) |
| | | 169 | | { |
| | 0 | 170 | | return true; |
| | | 171 | | } |
| | | 172 | | } |
| | | 173 | | |
| | 0 | 174 | | return false; |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | |
| | | 178 | | public async Task<List<Order>> ExcelToOrders(List<Dictionary<string, string>> table, |
| | | 179 | | OzonClient client, |
| | | 180 | | Manufacturer manufacturer, |
| | | 181 | | Warehouse warehouse, |
| | | 182 | | Supplier supplier, |
| | | 183 | | string clientStatus, |
| | | 184 | | CurrencyCode currencyCode, |
| | | 185 | | DateTime? selectedShippingDate, |
| | | 186 | | DateTime? selectedProcessingDate) |
| | | 187 | | |
| | | 188 | | { |
| | 0 | 189 | | string cacheKey = _appCache.GenerateCacheKey(table); |
| | | 190 | | |
| | | 191 | | |
| | 0 | 192 | | if (_appCache.GetCache().TryGetValue(cacheKey, out List<Order> cachedOrders)) |
| | | 193 | | |
| | | 194 | | { |
| | 0 | 195 | | Console.WriteLine($"Данные Excel найдены в кэше: {cacheKey}"); |
| | | 196 | | |
| | 0 | 197 | | return cachedOrders; |
| | | 198 | | } |
| | | 199 | | |
| | | 200 | | |
| | 0 | 201 | | List<Order> resultOrders = new List<Order>(); |
| | | 202 | | |
| | | 203 | | |
| | | 204 | | try |
| | | 205 | | |
| | | 206 | | { |
| | 0 | 207 | | foreach (var row in table) |
| | | 208 | | |
| | | 209 | | { |
| | 0 | 210 | | resultOrders.Add(await CastToModelFromExcel(row, client, manufacturer, warehouse, supplier, |
| | 0 | 211 | | clientStatus, currencyCode, selectedShippingDate, selectedProcessingDate)); |
| | | 212 | | } |
| | 0 | 213 | | } |
| | | 214 | | |
| | 0 | 215 | | catch (Exception ex) |
| | | 216 | | |
| | | 217 | | { |
| | 0 | 218 | | Console.WriteLine($"Ошибка при обработке данных из Excel: {ex.Message}"); |
| | 0 | 219 | | } |
| | | 220 | | |
| | | 221 | | |
| | 0 | 222 | | _appCache.GetCache().Set(cacheKey, resultOrders, TimeSpan.FromMinutes(10)); |
| | | 223 | | |
| | | 224 | | |
| | 0 | 225 | | return resultOrders; |
| | 0 | 226 | | } |
| | | 227 | | |
| | | 228 | | |
| | | 229 | | public async Task<List<Order>> ExcelToOrdersForDropbox(List<Dictionary<string, string>> table, |
| | | 230 | | OzonClient client, |
| | | 231 | | Manufacturer manufacturer, |
| | | 232 | | Warehouse warehouse, |
| | | 233 | | Supplier supplier, |
| | | 234 | | string clientStatus, |
| | | 235 | | CurrencyCode currencyCode, |
| | | 236 | | DateTime? selectedShippingDate, |
| | | 237 | | DateTime? selectedProcessingDate, |
| | | 238 | | string delivery) |
| | | 239 | | |
| | | 240 | | { |
| | 0 | 241 | | string cacheKey = _appCache.GenerateCacheKey(table); |
| | | 242 | | |
| | | 243 | | |
| | 0 | 244 | | if (_appCache.GetCache().TryGetValue(cacheKey, out List<Order> cachedOrders)) |
| | | 245 | | |
| | | 246 | | { |
| | 0 | 247 | | Console.WriteLine($"Данные Excel найдены в кэше: {cacheKey}"); |
| | | 248 | | |
| | 0 | 249 | | return cachedOrders; |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | |
| | 0 | 253 | | List<Order> resultOrders = new List<Order>(); |
| | | 254 | | |
| | | 255 | | |
| | | 256 | | try |
| | | 257 | | |
| | | 258 | | { |
| | 0 | 259 | | foreach (var row in table) |
| | | 260 | | |
| | | 261 | | { |
| | 0 | 262 | | resultOrders.Add(await CastToModelFromExcelForDropBox(row, client, manufacturer, warehouse, |
| | 0 | 263 | | supplier, |
| | 0 | 264 | | clientStatus, currencyCode, selectedShippingDate, selectedProcessingDate, delivery)); |
| | | 265 | | } |
| | 0 | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | catch (Exception ex) |
| | | 269 | | |
| | | 270 | | { |
| | 0 | 271 | | Console.WriteLine($"Ошибка при обработке данных из Excel: {ex.Message}"); |
| | 0 | 272 | | } |
| | | 273 | | |
| | | 274 | | |
| | 0 | 275 | | _appCache.GetCache().Set(cacheKey, resultOrders, TimeSpan.FromMinutes(10)); |
| | | 276 | | |
| | | 277 | | |
| | 0 | 278 | | return resultOrders; |
| | 0 | 279 | | } |
| | | 280 | | |
| | | 281 | | |
| | | 282 | | public async Task<List<Order>> YandexToOrders(JArray orders) |
| | | 283 | | |
| | | 284 | | { |
| | 0 | 285 | | List<Order> resultOrders = new List<Order>(); |
| | | 286 | | |
| | | 287 | | |
| | | 288 | | try |
| | | 289 | | |
| | | 290 | | { |
| | 0 | 291 | | foreach (var order in orders) |
| | | 292 | | |
| | | 293 | | { |
| | 0 | 294 | | resultOrders.Add(await CastToModelFromYandex(order)); |
| | | 295 | | } |
| | 0 | 296 | | } |
| | | 297 | | |
| | | 298 | | catch (Exception e) |
| | | 299 | | |
| | | 300 | | { |
| | 0 | 301 | | Console.WriteLine(e); |
| | | 302 | | |
| | 0 | 303 | | throw; |
| | | 304 | | } |
| | | 305 | | |
| | | 306 | | |
| | 0 | 307 | | return resultOrders; |
| | 0 | 308 | | } |
| | | 309 | | |
| | | 310 | | |
| | | 311 | | public async Task<List<Order>> XlsToOrdersForDropbox(List<Dictionary<string, string>> table, |
| | | 312 | | OzonClient client, |
| | | 313 | | Warehouse warehouse, |
| | | 314 | | DateTime selectedShippingDate, |
| | | 315 | | DateTime selectedProcessingDate, |
| | | 316 | | string delivery) |
| | | 317 | | |
| | | 318 | | { |
| | 0 | 319 | | string cacheKey = _appCache.GenerateCacheKey(table); |
| | | 320 | | |
| | | 321 | | |
| | 0 | 322 | | if (_appCache.GetCache().TryGetValue(cacheKey, out List<Order> cachedOrders)) |
| | | 323 | | |
| | | 324 | | { |
| | 0 | 325 | | Console.WriteLine($"Данные Excel найдены в кэше: {cacheKey}"); |
| | | 326 | | |
| | 0 | 327 | | return cachedOrders; |
| | | 328 | | } |
| | | 329 | | |
| | | 330 | | |
| | 0 | 331 | | List<Order> resultOrders = new List<Order>(); |
| | | 332 | | |
| | | 333 | | |
| | | 334 | | try |
| | | 335 | | |
| | | 336 | | { |
| | 0 | 337 | | foreach (var row in table) |
| | | 338 | | |
| | | 339 | | { |
| | 0 | 340 | | resultOrders.Add(await CastToModelFromExcelForEmEx(row, |
| | 0 | 341 | | client, |
| | 0 | 342 | | warehouse, |
| | 0 | 343 | | selectedShippingDate, |
| | 0 | 344 | | selectedProcessingDate, |
| | 0 | 345 | | delivery)); |
| | | 346 | | } |
| | 0 | 347 | | } |
| | | 348 | | |
| | 0 | 349 | | catch (Exception ex) |
| | | 350 | | |
| | | 351 | | { |
| | 0 | 352 | | Console.WriteLine($"Ошибка при обработке данных из Excel: {ex.Message}"); |
| | 0 | 353 | | } |
| | | 354 | | |
| | | 355 | | |
| | 0 | 356 | | _appCache.GetCache().Set(cacheKey, resultOrders, TimeSpan.FromMinutes(10)); |
| | | 357 | | |
| | | 358 | | |
| | 0 | 359 | | return resultOrders; |
| | 0 | 360 | | } |
| | | 361 | | |
| | | 362 | | |
| | | 363 | | public async Task<List<Order>> SetFileDataAsync(List<Order> orders, string filePath, string fileName) |
| | | 364 | | |
| | | 365 | | { |
| | 0 | 366 | | var fileMetadata = await _ordersFileMetadataDataService.GetOrdersFileMetadataAsync(new OrdersFileMetadata |
| | 0 | 367 | | |
| | 0 | 368 | | { |
| | 0 | 369 | | FileName = fileName, |
| | 0 | 370 | | |
| | 0 | 371 | | FolderName = filePath |
| | 0 | 372 | | }); |
| | | 373 | | |
| | | 374 | | |
| | 0 | 375 | | if (fileMetadata == null) |
| | | 376 | | |
| | | 377 | | { |
| | 0 | 378 | | fileMetadata = new OrdersFileMetadata |
| | 0 | 379 | | |
| | 0 | 380 | | { |
| | 0 | 381 | | FileName = fileName, |
| | 0 | 382 | | |
| | 0 | 383 | | FolderName = filePath |
| | 0 | 384 | | }; |
| | | 385 | | |
| | | 386 | | |
| | 0 | 387 | | await _ordersFileMetadataDataService.AddOrdersFileMetadata(fileMetadata); |
| | | 388 | | |
| | 0 | 389 | | fileMetadata = await _ordersFileMetadataDataService.GetOrdersFileMetadataAsync(fileMetadata); |
| | | 390 | | } |
| | | 391 | | |
| | | 392 | | |
| | 0 | 393 | | foreach (var order in orders) |
| | | 394 | | |
| | | 395 | | { |
| | 0 | 396 | | order.ExcelFileData = fileMetadata; |
| | | 397 | | } |
| | | 398 | | |
| | | 399 | | |
| | 0 | 400 | | return orders; |
| | 0 | 401 | | } |
| | | 402 | | |
| | | 403 | | |
| | | 404 | | /// <summary> |
| | | 405 | | /// Безопасно читает обязательное поле из JToken-источника. |
| | | 406 | | /// Если источник null или поле отсутствует/пусто — добавляет запись в <paramref name="missing"/> и возвращает n |
| | | 407 | | /// </summary> |
| | | 408 | | private static string? SafeField(JToken? source, string sourceName, string fieldName, List<string> missing) |
| | | 409 | | { |
| | 0 | 410 | | if (source == null) |
| | | 411 | | { |
| | 0 | 412 | | missing.Add($"{sourceName} отсутствует → поле «{fieldName}» недоступно"); |
| | 0 | 413 | | return null; |
| | | 414 | | } |
| | 0 | 415 | | var value = source[fieldName]?.ToString(); |
| | 0 | 416 | | if (string.IsNullOrWhiteSpace(value)) |
| | 0 | 417 | | missing.Add($"«{fieldName}» отсутствует или пусто в {sourceName}"); |
| | 0 | 418 | | return value; |
| | | 419 | | } |
| | | 420 | | |
| | | 421 | | /// <summary> |
| | | 422 | | /// Безопасно читает необязательное поле из JToken-источника. |
| | | 423 | | /// Пустое значение и null-источник — норма, возвращает null без предупреждений. |
| | | 424 | | /// </summary> |
| | | 425 | | private static string? SafeOptionalField(JToken? source, string fieldName) |
| | | 426 | | { |
| | 0 | 427 | | return source?[fieldName]?.ToString(); |
| | | 428 | | } |
| | | 429 | | |
| | | 430 | | [SuppressMessage("ReSharper.DPA", "DPA0006: Large number of DB commands", MessageId = "count: 178")] |
| | | 431 | | private async Task<Order> CastToModel(JToken? jsonOrder) |
| | | 432 | | { |
| | 0 | 433 | | Order order = new(); |
| | 0 | 434 | | CultureInfo culture = new("en-US"); |
| | | 435 | | |
| | 0 | 436 | | NumberStyles style = NumberStyles.Number; |
| | | 437 | | |
| | | 438 | | |
| | 0 | 439 | | order.Key = jsonOrder["Номер отправления"].ToString() + jsonOrder["Артикул"].ToString(); |
| | | 440 | | |
| | | 441 | | |
| | 0 | 442 | | order.ShipmentNumber = jsonOrder["Номер отправления"].ToString(); |
| | | 443 | | |
| | | 444 | | |
| | 0 | 445 | | order.ProcessingDate = DateTime.TryParse(jsonOrder["Принят в обработку"].ToString(), culture, |
| | 0 | 446 | | out var processingDate) |
| | 0 | 447 | | ? processingDate |
| | 0 | 448 | | : null; |
| | | 449 | | |
| | | 450 | | |
| | 0 | 451 | | order.ShippingDate = DateTime.TryParse(jsonOrder["Дата отгрузки"].ToString(), culture, out var shipingData) |
| | 0 | 452 | | ? shipingData |
| | 0 | 453 | | : null; |
| | | 454 | | |
| | 0 | 455 | | if (order.ShipmentNumber == "66929352-0158-1") |
| | | 456 | | { |
| | | 457 | | } |
| | | 458 | | |
| | 0 | 459 | | order.ClientStatus = await GetOrCreateClientStatusAsync(jsonOrder["Статус"]?.ToString()); |
| | | 460 | | |
| | | 461 | | |
| | 0 | 462 | | order.ShipmentAmount = decimal.TryParse(DelSubStr(jsonOrder["Сумма отправления"].ToString()), style, |
| | 0 | 463 | | culture, out var shipmentAmount) |
| | 0 | 464 | | ? shipmentAmount |
| | 0 | 465 | | : null; |
| | | 466 | | |
| | | 467 | | |
| | 0 | 468 | | order.ProductName = jsonOrder["Название товара"].ToString(); |
| | | 469 | | |
| | | 470 | | |
| | 0 | 471 | | order.ProductKey = jsonOrder["Артикул"].ToString(); |
| | | 472 | | |
| | 0 | 473 | | order.Quantity = int.TryParse(DelSubStr(jsonOrder["Количество"].ToString()), style, culture, |
| | 0 | 474 | | out var quantity) |
| | 0 | 475 | | ? quantity |
| | 0 | 476 | | : null; |
| | | 477 | | |
| | | 478 | | |
| | | 479 | | // Извлекаем значение из JSON до выполнения запроса к БД |
| | | 480 | | |
| | 0 | 481 | | string warehouseName = jsonOrder["productWarehousesAndCitysWithNumber"]?["delivery_method"]?["warehouse"] |
| | 0 | 482 | | ?.ToString(); |
| | | 483 | | |
| | | 484 | | |
| | 0 | 485 | | Warehouse shipmentWarehouse = null; |
| | | 486 | | |
| | 0 | 487 | | if (!string.IsNullOrEmpty(warehouseName)) |
| | | 488 | | |
| | | 489 | | { |
| | 0 | 490 | | shipmentWarehouse = _context.Warehouses.FirstOrDefault(w => w.Name == warehouseName); |
| | | 491 | | } |
| | | 492 | | |
| | | 493 | | |
| | 0 | 494 | | if (shipmentWarehouse != null) |
| | | 495 | | |
| | | 496 | | { |
| | 0 | 497 | | order.ShipmentWarehouse = shipmentWarehouse; |
| | | 498 | | } |
| | | 499 | | |
| | 0 | 500 | | else if (!string.IsNullOrEmpty(warehouseName)) |
| | | 501 | | |
| | | 502 | | { |
| | 0 | 503 | | var newWarehouse = new Warehouse |
| | 0 | 504 | | |
| | 0 | 505 | | { |
| | 0 | 506 | | Name = warehouseName |
| | 0 | 507 | | }; |
| | | 508 | | |
| | | 509 | | |
| | 0 | 510 | | _context.Warehouses.Add(newWarehouse); |
| | 0 | 511 | | await _context.SaveChangesAsync(); |
| | | 512 | | |
| | 0 | 513 | | order.ShipmentWarehouse = newWarehouse; |
| | 0 | 514 | | } |
| | | 515 | | |
| | | 516 | | |
| | 0 | 517 | | string extractedCode = Regex.Match(jsonOrder["Артикул"].ToString(), @"=(\w{3})").Groups[1].Value; |
| | | 518 | | |
| | | 519 | | |
| | 0 | 520 | | if (string.IsNullOrEmpty(extractedCode)) |
| | | 521 | | |
| | | 522 | | { |
| | 0 | 523 | | extractedCode = Regex.Match(jsonOrder["Артикул"].ToString(), @"=(\w{2})").Groups[1].Value; |
| | | 524 | | } |
| | | 525 | | |
| | | 526 | | |
| | 0 | 527 | | order = await SetEtProducerByCode(order, extractedCode); |
| | | 528 | | |
| | | 529 | | |
| | 0 | 530 | | string currencyCode = jsonOrder["Код валюты отправления"].ToString(); |
| | | 531 | | |
| | | 532 | | |
| | 0 | 533 | | Currency currency = _context.Currencys |
| | 0 | 534 | | .FirstOrDefault(c => c.Name == currencyCode); |
| | | 535 | | |
| | | 536 | | |
| | 0 | 537 | | if (currency != null) |
| | | 538 | | |
| | | 539 | | { |
| | 0 | 540 | | order.Сurrency = currency; |
| | | 541 | | } |
| | | 542 | | |
| | | 543 | | else |
| | | 544 | | |
| | | 545 | | { |
| | 0 | 546 | | var newCurrency = new Currency |
| | 0 | 547 | | |
| | 0 | 548 | | { |
| | 0 | 549 | | Name = currencyCode |
| | 0 | 550 | | }; |
| | | 551 | | |
| | | 552 | | |
| | 0 | 553 | | _context.Currencys.Add(newCurrency); |
| | 0 | 554 | | await _context.SaveChangesAsync(); |
| | | 555 | | |
| | 0 | 556 | | order.Сurrency = newCurrency; |
| | 0 | 557 | | } |
| | | 558 | | |
| | | 559 | | |
| | 0 | 560 | | order.Supplier = null; |
| | | 561 | | |
| | 0 | 562 | | order.PurchasePrice = null; |
| | | 563 | | |
| | | 564 | | |
| | 0 | 565 | | if (order.ProductInfo == null) |
| | | 566 | | |
| | | 567 | | { |
| | | 568 | | // Извлекаем значение из JSON до выполнения запроса к БД |
| | | 569 | | |
| | 0 | 570 | | string article = jsonOrder["Артикул"]?.ToString(); |
| | 0 | 571 | | string? ozonProductIdFromJson = jsonOrder["productWithArticle"]?["Ozon Product ID"]?.ToString(); |
| | | 572 | | |
| | 0 | 573 | | Product product = null; |
| | | 574 | | |
| | 0 | 575 | | if (!string.IsNullOrEmpty(article)) |
| | | 576 | | |
| | | 577 | | { |
| | 0 | 578 | | product = _context.Products.FirstOrDefault(p => p.Article == article); |
| | | 579 | | } |
| | | 580 | | |
| | | 581 | | |
| | 0 | 582 | | if (product != null) |
| | | 583 | | |
| | | 584 | | { |
| | | 585 | | // Дозаполняем OzonProductId, если оно отсутствует в уже существующем продукте. |
| | 0 | 586 | | if (string.IsNullOrWhiteSpace(product.OzonProductId) && |
| | 0 | 587 | | !string.IsNullOrWhiteSpace(ozonProductIdFromJson)) |
| | | 588 | | { |
| | 0 | 589 | | product.OzonProductId = ozonProductIdFromJson; |
| | | 590 | | } |
| | | 591 | | |
| | 0 | 592 | | if (string.IsNullOrEmpty(product.Barcode)) |
| | | 593 | | |
| | | 594 | | { |
| | 0 | 595 | | string barcode = jsonOrder["productWithArticle"]?["Штрихкод (Серийный номер / EAN)"]?.ToString() |
| | | 596 | | |
| | 0 | 597 | | if (!string.IsNullOrEmpty(barcode)) |
| | | 598 | | |
| | | 599 | | { |
| | 0 | 600 | | product.Barcode = barcode; |
| | | 601 | | } |
| | | 602 | | } |
| | | 603 | | |
| | | 604 | | // Если картинка не заполнена — подгружаем primary_image по Ozon product_id. |
| | 0 | 605 | | if (string.IsNullOrWhiteSpace(product.ImageUrl) && |
| | 0 | 606 | | !string.IsNullOrWhiteSpace(product.OzonProductId)) |
| | | 607 | | { |
| | 0 | 608 | | var primaryImage = jsonOrder["productWithArticle"]?["primary_image"]?.ToString(); |
| | 0 | 609 | | if (!string.IsNullOrWhiteSpace(primaryImage)) |
| | | 610 | | { |
| | 0 | 611 | | product.ImageUrl = primaryImage; |
| | | 612 | | } |
| | | 613 | | } |
| | | 614 | | |
| | | 615 | | // Дозаполняем категорию, если она пуста в существующем продукте |
| | 0 | 616 | | if (string.IsNullOrWhiteSpace(product.CommercialCategory)) |
| | | 617 | | { |
| | 0 | 618 | | var category = jsonOrder["productWithArticle"]?["Категория"]?.ToString(); |
| | 0 | 619 | | if (!string.IsNullOrWhiteSpace(category)) |
| | | 620 | | { |
| | 0 | 621 | | product.CommercialCategory = category; |
| | | 622 | | } |
| | | 623 | | } |
| | | 624 | | |
| | | 625 | | |
| | 0 | 626 | | order.ProductInfo = product; |
| | | 627 | | } |
| | | 628 | | |
| | | 629 | | else |
| | | 630 | | |
| | | 631 | | { |
| | 0 | 632 | | var missingFields = new List<string>(); |
| | 0 | 633 | | var pw = jsonOrder["productWithArticle"]; |
| | | 634 | | |
| | 0 | 635 | | product = new Product(); |
| | | 636 | | |
| | 0 | 637 | | product.Article = jsonOrder["Артикул"]?.ToString() ?? ""; |
| | | 638 | | |
| | 0 | 639 | | product.OzonProductId = SafeField(pw, "productWithArticle", "Ozon Product ID", missingFields) ?? ""; |
| | | 640 | | |
| | 0 | 641 | | var sku = SafeField(pw, "productWithArticle", "SKU", missingFields) ?? ""; |
| | 0 | 642 | | product.FboOzonSkuId = sku; |
| | 0 | 643 | | product.FbsOzonSkuId = sku; |
| | | 644 | | |
| | 0 | 645 | | product.CommercialCategory = SafeField(pw, "productWithArticle", "Категория", missingFields) ?? ""; |
| | | 646 | | |
| | | 647 | | // необязательные поля — пустое значение норма, предупреждение только если источник null |
| | 0 | 648 | | var barcode = SafeOptionalField(pw, "Штрихкод (Серийный номер / EAN)"); |
| | 0 | 649 | | if (!string.IsNullOrEmpty(barcode)) |
| | 0 | 650 | | product.Barcode = barcode; |
| | | 651 | | |
| | | 652 | | // Для нового продукта сразу заполняем картинку, если поле пустое. |
| | 0 | 653 | | var primaryImage = pw?["primary_image"]?.ToString(); |
| | 0 | 654 | | if (!string.IsNullOrWhiteSpace(primaryImage)) |
| | 0 | 655 | | product.ImageUrl = primaryImage; |
| | | 656 | | |
| | 0 | 657 | | var volumeStr = SafeOptionalField(pw, "Объем товара, л"); |
| | 0 | 658 | | product.Volume = double.TryParse(DelSubStr(volumeStr ?? ""), style, culture, out double volume) |
| | 0 | 659 | | ? volume |
| | 0 | 660 | | : null; |
| | | 661 | | |
| | 0 | 662 | | var volWeightStr = SafeOptionalField(pw, "Объемный вес, кг"); |
| | 0 | 663 | | product.VolumetricWeight = double.TryParse(DelSubStr(volWeightStr ?? ""), style, culture, out double |
| | 0 | 664 | | ? volumetricWeight |
| | 0 | 665 | | : null; |
| | | 666 | | |
| | 0 | 667 | | _context.Products.Add(product); |
| | | 668 | | // В проде ловили SQL-синтаксис возле RETURNING при пакетной вставке нескольких новых сущностей. |
| | | 669 | | // Фикс: сохраняем новый Product отдельной командой до следующих INSERT. |
| | 0 | 670 | | await _context.SaveChangesAsync(); |
| | 0 | 671 | | order.ProductInfo = product; |
| | | 672 | | |
| | 0 | 673 | | if (missingFields.Count > 0) |
| | | 674 | | { |
| | 0 | 675 | | var shipNum = jsonOrder["Номер отправления"]?.ToString() ?? "?"; |
| | 0 | 676 | | var art = jsonOrder["Артикул"]?.ToString() ?? "?"; |
| | 0 | 677 | | var subject = $"[OrderCaster] Пропущены поля при создании товара — заказ {shipNum}, артикул {art |
| | 0 | 678 | | var body = $"Заказ: {shipNum}\nАртикул: {art}\n\nПропущенные поля из отчёта Ozon:\n• {string.Joi |
| | 0 | 679 | | $"Возможные причины:\n— Ozon переименовал колонку в отчёте /v1/report/products/create |
| | 0 | 680 | | await _emailService.SendEmailAsync(subject, body); |
| | | 681 | | } |
| | 0 | 682 | | } |
| | 0 | 683 | | } |
| | | 684 | | |
| | | 685 | | |
| | 0 | 686 | | var wc = jsonOrder["productWarehousesAndCitysWithNumber"]; |
| | 0 | 687 | | var city = wc?["analytics_data"]?["city"]?.ToString(); |
| | 0 | 688 | | var region = wc?["analytics_data"]?["region"]?.ToString(); |
| | 0 | 689 | | var clusterTo = wc?["financial_data"]?["cluster_to"]?.ToString(); |
| | | 690 | | |
| | | 691 | | |
| | 0 | 692 | | order.DeliveryCity = !string.IsNullOrEmpty(city) |
| | 0 | 693 | | ? city |
| | 0 | 694 | | : !string.IsNullOrEmpty(region) |
| | 0 | 695 | | ? region |
| | 0 | 696 | | : clusterTo; |
| | | 697 | | |
| | 0 | 698 | | var trackingNumber = jsonOrder["productWarehousesAndCitysWithNumber"]?["tracking_number"]?.ToString(); |
| | 0 | 699 | | order.TrackingNumber = string.IsNullOrEmpty(trackingNumber) ? null : trackingNumber; |
| | | 700 | | |
| | | 701 | | // ScanIt приходит в том же ответе /v3/posting/fbs/get; пустое значение не затирает |
| | | 702 | | // уже сохранённое: при обновлении заказа в БД переносятся только непустые поля. |
| | 0 | 703 | | var scanit = wc?["scanit"]?.ToString(); |
| | 0 | 704 | | order.Scanit = string.IsNullOrWhiteSpace(scanit) ? null : scanit.Trim(); |
| | | 705 | | |
| | | 706 | | |
| | 0 | 707 | | if (order.AppStatus == null) |
| | | 708 | | |
| | | 709 | | { |
| | 0 | 710 | | string statusName = "Не указан"; |
| | | 711 | | |
| | | 712 | | |
| | 0 | 713 | | AppStatus appStatus = _context.AppStatuses.FirstOrDefault(c => c.Name == statusName); |
| | | 714 | | |
| | | 715 | | |
| | 0 | 716 | | if (appStatus != null) |
| | | 717 | | |
| | | 718 | | { |
| | 0 | 719 | | order.AppStatus = appStatus; |
| | | 720 | | } |
| | | 721 | | |
| | | 722 | | else |
| | | 723 | | |
| | | 724 | | { |
| | 0 | 725 | | var newStatus = new AppStatus |
| | 0 | 726 | | |
| | 0 | 727 | | { |
| | 0 | 728 | | Name = statusName |
| | 0 | 729 | | }; |
| | | 730 | | |
| | | 731 | | |
| | 0 | 732 | | _context.AppStatuses.Add(newStatus); |
| | 0 | 733 | | await _context.SaveChangesAsync(); |
| | | 734 | | |
| | 0 | 735 | | order.AppStatus = newStatus; |
| | 0 | 736 | | } |
| | | 737 | | } |
| | | 738 | | |
| | | 739 | | |
| | 0 | 740 | | if (order.Supplier == null) |
| | | 741 | | |
| | | 742 | | { |
| | 0 | 743 | | string supplierName = "Не указан"; |
| | | 744 | | |
| | | 745 | | |
| | 0 | 746 | | Supplier supplier = _context.Suppliers.FirstOrDefault(c => c.Name == supplierName); |
| | | 747 | | |
| | | 748 | | |
| | 0 | 749 | | if (supplier != null) |
| | | 750 | | |
| | | 751 | | { |
| | 0 | 752 | | order.Supplier = supplier; |
| | | 753 | | } |
| | | 754 | | |
| | | 755 | | else |
| | | 756 | | |
| | | 757 | | { |
| | 0 | 758 | | var newSupplier = new Supplier |
| | 0 | 759 | | |
| | 0 | 760 | | { |
| | 0 | 761 | | Name = supplierName |
| | 0 | 762 | | }; |
| | | 763 | | |
| | | 764 | | |
| | 0 | 765 | | _context.Suppliers.Add(newSupplier); |
| | 0 | 766 | | await _context.SaveChangesAsync(); |
| | | 767 | | |
| | 0 | 768 | | order.Supplier = newSupplier; |
| | 0 | 769 | | } |
| | | 770 | | } |
| | | 771 | | |
| | | 772 | | |
| | 0 | 773 | | var deliveryName = jsonOrder["productWarehousesAndCitysWithNumber"]["delivery_method"]["name"]?.ToString(); |
| | | 774 | | |
| | 0 | 775 | | var deliveryProvider = jsonOrder["productWarehousesAndCitysWithNumber"]["delivery_method"]["tpl_provider"] |
| | 0 | 776 | | ?.ToString(); |
| | | 777 | | |
| | | 778 | | |
| | 0 | 779 | | if (!string.IsNullOrWhiteSpace(deliveryName)) |
| | | 780 | | |
| | | 781 | | { |
| | 0 | 782 | | var delivery = await _deliveryService.GetOrCreateDeliveryAsync(deliveryName, deliveryProvider); |
| | | 783 | | |
| | | 784 | | |
| | 0 | 785 | | order.Delivery = delivery; |
| | | 786 | | |
| | 0 | 787 | | order.DeliveryId = delivery.Id; |
| | | 788 | | } |
| | | 789 | | |
| | | 790 | | |
| | 0 | 791 | | order = SetCorrectProductKey(order); |
| | | 792 | | |
| | 0 | 793 | | await CreateOrderPriceAndIndexes(order, jsonOrder); |
| | | 794 | | |
| | | 795 | | // Снимок не использует OrderPrice: он фиксирует полный ответ Ozon и условия акций |
| | | 796 | | // отдельно, чтобы повторная загрузка заказа не изменила историю продажи. |
| | | 797 | | // Webhook и ручной импорт могут повторно прислать то же отправление: для такого |
| | | 798 | | // заказа снимок уже существует и уникальный индекс OrderId не допускает второй. |
| | 0 | 799 | | var snapshotAlreadyCaptured = await _context.OrderOzonPromotionSnapshots |
| | 0 | 800 | | .AsNoTracking() |
| | 0 | 801 | | .AnyAsync(snapshot => snapshot.Order.Key == order.Key); |
| | 0 | 802 | | if (!snapshotAlreadyCaptured) |
| | | 803 | | { |
| | 0 | 804 | | order.OzonPromotionSnapshot = CreateOzonPromotionSnapshot(jsonOrder); |
| | | 805 | | } |
| | | 806 | | |
| | | 807 | | |
| | 0 | 808 | | var (price, priceWithDiscount, maxComment, minComment, min, max) = CalculateСommissions(jsonOrder, order); |
| | | 809 | | |
| | | 810 | | |
| | 0 | 811 | | order.Price = price; |
| | | 812 | | |
| | 0 | 813 | | order.ProductInfo.CurrentPriceWithDiscount = priceWithDiscount; |
| | | 814 | | |
| | | 815 | | |
| | 0 | 816 | | order.MaxOzonCommission = max; |
| | | 817 | | |
| | 0 | 818 | | order.MinOzonCommission = min; |
| | | 819 | | |
| | 0 | 820 | | order.MaxCommissionInfo = maxComment; |
| | | 821 | | |
| | 0 | 822 | | order.MinCommissionInfo = minComment; |
| | | 823 | | |
| | 0 | 824 | | order.UpdatedBy = "Ozon"; |
| | | 825 | | |
| | 0 | 826 | | await _context.SaveChangesAsync(); |
| | | 827 | | |
| | | 828 | | |
| | 0 | 829 | | return order; |
| | 0 | 830 | | } |
| | | 831 | | |
| | | 832 | | |
| | | 833 | | /// <summary> |
| | | 834 | | /// Цена позиции из заказа Яндекс.Маркета: prices.payment (оплата покупателем) + prices.subsidy (субсидия Маркет |
| | | 835 | | /// </summary> |
| | | 836 | | private static decimal? GetYandexOrderItemPrice(JToken? item) |
| | | 837 | | { |
| | 0 | 838 | | var payment = item?["prices"]?["payment"]?["value"]?.Value<decimal>(); |
| | | 839 | | |
| | 0 | 840 | | if (payment is null or <= 0) |
| | | 841 | | { |
| | 0 | 842 | | return null; |
| | | 843 | | } |
| | | 844 | | |
| | 0 | 845 | | var subsidy = item?["prices"]?["subsidy"]?["value"]?.Value<decimal>() ?? 0; |
| | | 846 | | |
| | 0 | 847 | | return payment.Value + subsidy; |
| | | 848 | | } |
| | | 849 | | |
| | | 850 | | public async Task<Order> CastToModelFromYandex(JToken? jsonOrder) |
| | | 851 | | |
| | | 852 | | { |
| | 0 | 853 | | Order order = new(); |
| | | 854 | | |
| | | 855 | | |
| | 0 | 856 | | CultureInfo culture = new("en-US"); |
| | | 857 | | |
| | 0 | 858 | | NumberStyles style = NumberStyles.Number; |
| | | 859 | | |
| | | 860 | | // Добавлены форматы с timezone offset (например, +03:00) |
| | | 861 | | |
| | 0 | 862 | | var dateFormats = new[] |
| | 0 | 863 | | |
| | 0 | 864 | | { |
| | 0 | 865 | | "yyyy-MM-ddTHH:mm:ss.fffzzz", // С миллисекундами и timezone с : (2026-01-14T21:21:30.209+03:00) |
| | 0 | 866 | | |
| | 0 | 867 | | "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", // Дополнительные варианты |
| | 0 | 868 | | |
| | 0 | 869 | | "yyyy-MM-ddTHH:mm:ss.FFFK", |
| | 0 | 870 | | |
| | 0 | 871 | | "yyyy-MM-ddTHH:mm:ssK", |
| | 0 | 872 | | |
| | 0 | 873 | | "yyyy-MM-ddTHH:mm:ss.FFFFFFF", |
| | 0 | 874 | | |
| | 0 | 875 | | "yyyy-MM-ddTHH:mm:ss.FFF", |
| | 0 | 876 | | |
| | 0 | 877 | | "yyyy-MM-ddTHH:mm:ss", |
| | 0 | 878 | | |
| | 0 | 879 | | "yyyy-MM-dd", |
| | 0 | 880 | | |
| | 0 | 881 | | "dd.MM.yyyy", // 14.01.2026 |
| | 0 | 882 | | |
| | 0 | 883 | | "MM/dd/yyyy", // 01/14/2026 |
| | 0 | 884 | | |
| | 0 | 885 | | "yyyy/MM/dd" |
| | 0 | 886 | | }; |
| | | 887 | | |
| | | 888 | | |
| | | 889 | | // 1. Исправление: проверка на null для обязательных полей |
| | | 890 | | |
| | 0 | 891 | | if (jsonOrder == null) |
| | | 892 | | |
| | 0 | 893 | | return order; |
| | | 894 | | |
| | | 895 | | |
| | 0 | 896 | | order.Key = jsonOrder["orderId"]?.ToString() + jsonOrder["items"]?[0]?["offerId"]?.ToString(); |
| | | 897 | | |
| | | 898 | | |
| | 0 | 899 | | order.ShipmentNumber = jsonOrder["orderId"]?.ToString(); |
| | | 900 | | |
| | | 901 | | |
| | 0 | 902 | | if (jsonOrder["creationDate"] != null) |
| | | 903 | | |
| | | 904 | | { |
| | 0 | 905 | | var creationDateStr = jsonOrder["creationDate"].ToString(); |
| | | 906 | | |
| | | 907 | | |
| | | 908 | | // Определяем разделитель (T или пробел) |
| | | 909 | | |
| | 0 | 910 | | char separator = 'T'; |
| | | 911 | | |
| | 0 | 912 | | if (creationDateStr.Contains(' ')) |
| | | 913 | | |
| | | 914 | | { |
| | 0 | 915 | | separator = ' '; |
| | | 916 | | } |
| | | 917 | | |
| | 0 | 918 | | else if (creationDateStr.Contains('T')) |
| | | 919 | | |
| | | 920 | | { |
| | 0 | 921 | | separator = 'T'; |
| | | 922 | | } |
| | | 923 | | |
| | | 924 | | |
| | | 925 | | // Извлекаем только дату (часть до разделителя) |
| | | 926 | | |
| | | 927 | | string dateOnlyStr; |
| | | 928 | | |
| | 0 | 929 | | if (creationDateStr.Contains(separator)) |
| | | 930 | | |
| | | 931 | | { |
| | 0 | 932 | | dateOnlyStr = creationDateStr.Split(separator)[0]; // Берем часть до разделителя |
| | | 933 | | } |
| | | 934 | | |
| | | 935 | | else |
| | | 936 | | |
| | | 937 | | { |
| | 0 | 938 | | dateOnlyStr = creationDateStr; // Если нет разделителя, берем всю строку |
| | | 939 | | } |
| | | 940 | | |
| | | 941 | | |
| | 0 | 942 | | if (DateTime.TryParseExact( |
| | 0 | 943 | | dateOnlyStr, |
| | 0 | 944 | | dateFormats, |
| | 0 | 945 | | CultureInfo.InvariantCulture, |
| | 0 | 946 | | DateTimeStyles.None, |
| | 0 | 947 | | out var processingDate)) |
| | | 948 | | |
| | | 949 | | { |
| | 0 | 950 | | order.ProcessingDate = processingDate; |
| | | 951 | | } |
| | | 952 | | |
| | | 953 | | else |
| | | 954 | | |
| | | 955 | | { |
| | | 956 | | // Если не получилось через TryParseExact, пробуем обычный Parse |
| | | 957 | | |
| | 0 | 958 | | if (DateTime.TryParse(dateOnlyStr, CultureInfo.InvariantCulture, DateTimeStyles.None, |
| | 0 | 959 | | out processingDate)) |
| | | 960 | | |
| | | 961 | | { |
| | 0 | 962 | | order.ProcessingDate = processingDate; |
| | | 963 | | } |
| | | 964 | | } |
| | | 965 | | } |
| | | 966 | | |
| | | 967 | | |
| | | 968 | | // 3. Исправление: проверка вложенных полей доступа для даты отгрузки |
| | | 969 | | |
| | | 970 | | // Сначала проверяем delivery.shipment.shipmentDate (новый формат) |
| | | 971 | | |
| | 0 | 972 | | if (jsonOrder["delivery"]?["shipment"]?["shipmentDate"] != null) |
| | | 973 | | |
| | | 974 | | { |
| | 0 | 975 | | var shipmentDateStr = jsonOrder["delivery"]["shipment"]["shipmentDate"]?.ToString(); |
| | | 976 | | |
| | 0 | 977 | | if (!string.IsNullOrEmpty(shipmentDateStr)) |
| | | 978 | | |
| | | 979 | | { |
| | 0 | 980 | | if (DateTimeOffset.TryParse( |
| | 0 | 981 | | shipmentDateStr, |
| | 0 | 982 | | CultureInfo.InvariantCulture, |
| | 0 | 983 | | DateTimeStyles.RoundtripKind, |
| | 0 | 984 | | out var shippingOffset) |
| | 0 | 985 | | || DateTimeOffset.TryParseExact( |
| | 0 | 986 | | shipmentDateStr, |
| | 0 | 987 | | dateFormats, |
| | 0 | 988 | | CultureInfo.InvariantCulture, |
| | 0 | 989 | | DateTimeStyles.RoundtripKind, |
| | 0 | 990 | | out shippingOffset)) |
| | | 991 | | |
| | | 992 | | { |
| | 0 | 993 | | order.ShippingDate = shippingOffset.DateTime; |
| | | 994 | | } |
| | | 995 | | } |
| | | 996 | | } |
| | | 997 | | |
| | | 998 | | // Если не нашли, проверяем старый формат delivery.shipments |
| | | 999 | | |
| | 0 | 1000 | | else if (jsonOrder["delivery"]?["shipments"] != null) |
| | | 1001 | | |
| | | 1002 | | { |
| | 0 | 1003 | | var shipmentDateStr = jsonOrder["delivery"]["shipments"]?.FirstOrDefault()?["shipmentDate"]?.ToString(); |
| | | 1004 | | |
| | 0 | 1005 | | if (!string.IsNullOrEmpty(shipmentDateStr)) |
| | | 1006 | | |
| | | 1007 | | { |
| | 0 | 1008 | | if (DateTimeOffset.TryParse( |
| | 0 | 1009 | | shipmentDateStr, |
| | 0 | 1010 | | CultureInfo.InvariantCulture, |
| | 0 | 1011 | | DateTimeStyles.RoundtripKind, |
| | 0 | 1012 | | out var shippingOffset) |
| | 0 | 1013 | | || DateTimeOffset.TryParseExact( |
| | 0 | 1014 | | shipmentDateStr, |
| | 0 | 1015 | | dateFormats, |
| | 0 | 1016 | | CultureInfo.InvariantCulture, |
| | 0 | 1017 | | DateTimeStyles.RoundtripKind, |
| | 0 | 1018 | | out shippingOffset)) |
| | | 1019 | | |
| | | 1020 | | { |
| | 0 | 1021 | | order.ShippingDate = shippingOffset.DateTime; |
| | | 1022 | | } |
| | | 1023 | | } |
| | | 1024 | | } |
| | | 1025 | | |
| | | 1026 | | |
| | | 1027 | | // 4. Исправление: безопасный доступ к статусу |
| | | 1028 | | |
| | 0 | 1029 | | string status = jsonOrder["status"]?.ToString() ?? "UNKNOWN"; |
| | | 1030 | | |
| | 0 | 1031 | | order.ClientStatus = await GetOrCreateClientStatusAsync(YandexStatus.GetStatus(status)); |
| | | 1032 | | |
| | | 1033 | | |
| | | 1034 | | // 5. Исправление: безопасный доступ к полям items |
| | | 1035 | | |
| | 0 | 1036 | | var firstItem = jsonOrder["items"]?[0]; |
| | | 1037 | | |
| | 0 | 1038 | | if (firstItem != null) |
| | | 1039 | | |
| | | 1040 | | { |
| | 0 | 1041 | | order.ProductName = firstItem["offerName"]?.ToString() ?? string.Empty; |
| | | 1042 | | |
| | 0 | 1043 | | order.ProductKey = firstItem["offerId"]?.ToString() ?? string.Empty; |
| | | 1044 | | |
| | 0 | 1045 | | order.Article = firstItem["offerId"]?.ToString() ?? string.Empty; |
| | | 1046 | | |
| | | 1047 | | |
| | 0 | 1048 | | if (int.TryParse(DelSubStr(firstItem["count"]?.ToString() ?? "0"), style, culture, out var quantity)) |
| | | 1049 | | |
| | | 1050 | | { |
| | 0 | 1051 | | order.Quantity = quantity; |
| | | 1052 | | } |
| | | 1053 | | |
| | | 1054 | | |
| | | 1055 | | // 6. Склад отгрузки из campaign. Для кампаний из YandexCampaignWarehouses |
| | | 1056 | | // имя кампании — доставка, а склад отгрузки в Studio2 должен совпадать |
| | | 1057 | | // с фактическим складом (V11, M1), а не с названием кампании. |
| | | 1058 | | |
| | 0 | 1059 | | var campaignName = jsonOrder["campaign"]?["domain"]?.ToString() ?? string.Empty; |
| | 0 | 1060 | | var warehouseName = campaignName; |
| | | 1061 | | |
| | 0 | 1062 | | if (YandexCampaignWarehouses.TryGetValue(campaignName, out var mappedWarehouseName)) |
| | | 1063 | | { |
| | 0 | 1064 | | warehouseName = mappedWarehouseName; |
| | | 1065 | | |
| | 0 | 1066 | | var delivery = await _deliveryService.GetOrCreateDeliveryAsync(campaignName, |
| | 0 | 1067 | | YandexDeliveryProviderName); |
| | 0 | 1068 | | order.Delivery = delivery; |
| | 0 | 1069 | | order.DeliveryId = delivery.Id; |
| | | 1070 | | } |
| | | 1071 | | |
| | | 1072 | | |
| | 0 | 1073 | | if (!string.IsNullOrEmpty(warehouseName)) |
| | | 1074 | | |
| | | 1075 | | { |
| | 0 | 1076 | | var shipmentWarehouse = _context.Warehouses.FirstOrDefault(w => w.Name == warehouseName); |
| | | 1077 | | |
| | | 1078 | | |
| | 0 | 1079 | | if (shipmentWarehouse != null) |
| | | 1080 | | |
| | | 1081 | | { |
| | 0 | 1082 | | order.ShipmentWarehouse = shipmentWarehouse; |
| | | 1083 | | } |
| | | 1084 | | |
| | | 1085 | | else |
| | | 1086 | | |
| | | 1087 | | { |
| | 0 | 1088 | | var newWarehouse = new Warehouse { Name = warehouseName }; |
| | | 1089 | | |
| | 0 | 1090 | | _context.Warehouses.Add(newWarehouse); |
| | | 1091 | | |
| | 0 | 1092 | | await _context.SaveChangesAsync(); |
| | | 1093 | | |
| | 0 | 1094 | | order.ShipmentWarehouse = newWarehouse; |
| | 0 | 1095 | | } |
| | | 1096 | | } |
| | | 1097 | | |
| | | 1098 | | |
| | | 1099 | | // 7. Исправление: извлечение кода производителя |
| | | 1100 | | |
| | 0 | 1101 | | string extractedCode = string.Empty; |
| | | 1102 | | |
| | 0 | 1103 | | string offerId = firstItem["offerId"]?.ToString() ?? string.Empty; |
| | | 1104 | | |
| | | 1105 | | |
| | 0 | 1106 | | if (!string.IsNullOrEmpty(offerId)) |
| | | 1107 | | |
| | | 1108 | | { |
| | 0 | 1109 | | var match3 = Regex.Match(offerId, @"=(\w{3})"); |
| | | 1110 | | |
| | 0 | 1111 | | if (match3.Success) |
| | | 1112 | | |
| | | 1113 | | { |
| | 0 | 1114 | | extractedCode = match3.Groups[1].Value; |
| | | 1115 | | } |
| | | 1116 | | |
| | | 1117 | | else |
| | | 1118 | | |
| | | 1119 | | { |
| | 0 | 1120 | | var match2 = Regex.Match(offerId, @"=(\w{2})"); |
| | | 1121 | | |
| | 0 | 1122 | | if (match2.Success) |
| | | 1123 | | |
| | | 1124 | | { |
| | 0 | 1125 | | extractedCode = match2.Groups[1].Value; |
| | | 1126 | | } |
| | | 1127 | | } |
| | | 1128 | | } |
| | | 1129 | | |
| | | 1130 | | |
| | 0 | 1131 | | if (!string.IsNullOrEmpty(extractedCode)) |
| | | 1132 | | |
| | | 1133 | | { |
| | 0 | 1134 | | var manufacturer = _context.Manufacturers.FirstOrDefault(m => m.Code == extractedCode); |
| | | 1135 | | |
| | | 1136 | | |
| | 0 | 1137 | | if (manufacturer != null) |
| | | 1138 | | |
| | | 1139 | | { |
| | 0 | 1140 | | order.Manufacturer = manufacturer; |
| | | 1141 | | } |
| | | 1142 | | |
| | | 1143 | | else |
| | | 1144 | | |
| | | 1145 | | { |
| | 0 | 1146 | | var newManufacturer = new Manufacturer { Code = extractedCode }; |
| | | 1147 | | |
| | 0 | 1148 | | _context.Manufacturers.Add(newManufacturer); |
| | | 1149 | | |
| | 0 | 1150 | | await _context.SaveChangesAsync(); |
| | | 1151 | | |
| | 0 | 1152 | | order.Manufacturer = newManufacturer; |
| | 0 | 1153 | | } |
| | | 1154 | | |
| | | 1155 | | |
| | 0 | 1156 | | order = await SetEtProducerByCode(order, extractedCode); |
| | | 1157 | | } |
| | | 1158 | | |
| | | 1159 | | |
| | | 1160 | | // 8. Исправление: валюта |
| | | 1161 | | |
| | 0 | 1162 | | string currencyCode = firstItem["prices"]?["payment"]?["currencyId"]?.ToString() ?? "RUR"; |
| | | 1163 | | |
| | | 1164 | | |
| | 0 | 1165 | | var currency = _context.Currencys.FirstOrDefault(c => c.Name == currencyCode); |
| | | 1166 | | |
| | | 1167 | | |
| | 0 | 1168 | | if (currency != null) |
| | | 1169 | | |
| | | 1170 | | { |
| | 0 | 1171 | | order.Сurrency = currency; |
| | | 1172 | | } |
| | | 1173 | | |
| | | 1174 | | else |
| | | 1175 | | |
| | | 1176 | | { |
| | 0 | 1177 | | var newCurrency = new Currency { Name = currencyCode }; |
| | | 1178 | | |
| | 0 | 1179 | | _context.Currencys.Add(newCurrency); |
| | | 1180 | | |
| | 0 | 1181 | | order.Сurrency = newCurrency; |
| | | 1182 | | } |
| | | 1183 | | |
| | | 1184 | | |
| | 0 | 1185 | | order.Supplier = null; |
| | | 1186 | | |
| | 0 | 1187 | | order.PurchasePrice = null; |
| | | 1188 | | |
| | | 1189 | | |
| | | 1190 | | // 9. Исправление: ProductInfo |
| | | 1191 | | |
| | 0 | 1192 | | if (order.ProductInfo == null) |
| | | 1193 | | |
| | | 1194 | | { |
| | 0 | 1195 | | string article = firstItem["offerId"]?.ToString() ?? string.Empty; |
| | | 1196 | | |
| | 0 | 1197 | | var primaryImageUrl = GetYandexPrimaryImageUrl(firstItem); |
| | | 1198 | | |
| | 0 | 1199 | | var product = _context.Products.FirstOrDefault(p => p.Article == article); |
| | | 1200 | | |
| | | 1201 | | |
| | 0 | 1202 | | if (product != null) |
| | | 1203 | | |
| | | 1204 | | { |
| | | 1205 | | // Аналогично Ozon: не перезаписываем уже заданное фото, |
| | | 1206 | | // но дополняем карточку изображением из offer-mappings Яндекс.Маркета. |
| | 0 | 1207 | | if (string.IsNullOrWhiteSpace(product.ImageUrl) && !string.IsNullOrWhiteSpace(primaryImageUrl)) |
| | | 1208 | | { |
| | 0 | 1209 | | product.ImageUrl = primaryImageUrl; |
| | | 1210 | | } |
| | | 1211 | | |
| | 0 | 1212 | | order.ProductInfo = product; |
| | | 1213 | | } |
| | | 1214 | | |
| | | 1215 | | else |
| | | 1216 | | |
| | | 1217 | | { |
| | 0 | 1218 | | var offerMapping = firstItem["offerMapping"]; |
| | | 1219 | | |
| | 0 | 1220 | | var mapping = offerMapping?["mapping"]; |
| | | 1221 | | |
| | 0 | 1222 | | var offer = offerMapping?["offer"]; |
| | | 1223 | | |
| | | 1224 | | |
| | 0 | 1225 | | product = new Product |
| | 0 | 1226 | | |
| | 0 | 1227 | | { |
| | 0 | 1228 | | Article = article, |
| | 0 | 1229 | | |
| | 0 | 1230 | | CommercialCategory = mapping?["marketCategoryName"]?.ToString() ?? string.Empty, |
| | 0 | 1231 | | |
| | 0 | 1232 | | ImageUrl = primaryImageUrl |
| | 0 | 1233 | | }; |
| | | 1234 | | |
| | | 1235 | | |
| | | 1236 | | // Баркод из delivery.boxesLayout[0].barcode |
| | | 1237 | | |
| | 0 | 1238 | | var barcode = jsonOrder["delivery"]?["boxesLayout"]?[0]?["barcode"]?.ToString(); |
| | | 1239 | | |
| | 0 | 1240 | | if (!string.IsNullOrEmpty(barcode)) |
| | | 1241 | | |
| | | 1242 | | { |
| | 0 | 1243 | | product.Barcode = barcode; |
| | | 1244 | | } |
| | | 1245 | | |
| | | 1246 | | |
| | | 1247 | | // Вес из weightDimensions |
| | | 1248 | | |
| | 0 | 1249 | | var weightDimensions = offer?["weightDimensions"]; |
| | | 1250 | | |
| | 0 | 1251 | | if (weightDimensions != null) |
| | | 1252 | | |
| | | 1253 | | { |
| | 0 | 1254 | | var weightStr = weightDimensions["weight"]?.ToString(); |
| | | 1255 | | |
| | 0 | 1256 | | if (!string.IsNullOrEmpty(weightStr)) |
| | | 1257 | | |
| | | 1258 | | { |
| | 0 | 1259 | | if (double.TryParse(DelSubStr(weightStr), style, culture, out var weight)) |
| | | 1260 | | |
| | | 1261 | | { |
| | 0 | 1262 | | product.Weight = (decimal)weight; |
| | | 1263 | | |
| | 0 | 1264 | | product.VolumetricWeight = weight; |
| | | 1265 | | |
| | | 1266 | | |
| | | 1267 | | // Объем из габаритов (length * width * height / 1000000 для перевода в литры) |
| | | 1268 | | |
| | 0 | 1269 | | var lengthStr = weightDimensions["length"]?.ToString(); |
| | | 1270 | | |
| | 0 | 1271 | | var widthStr = weightDimensions["width"]?.ToString(); |
| | | 1272 | | |
| | 0 | 1273 | | var heightStr = weightDimensions["height"]?.ToString(); |
| | | 1274 | | |
| | | 1275 | | |
| | 0 | 1276 | | if (!string.IsNullOrEmpty(lengthStr) && !string.IsNullOrEmpty(widthStr) && |
| | 0 | 1277 | | !string.IsNullOrEmpty(heightStr)) |
| | | 1278 | | |
| | | 1279 | | { |
| | 0 | 1280 | | if (double.TryParse(DelSubStr(lengthStr), style, culture, out var length) && |
| | 0 | 1281 | | double.TryParse(DelSubStr(widthStr), style, culture, out var width) && |
| | 0 | 1282 | | double.TryParse(DelSubStr(heightStr), style, culture, out var height)) |
| | | 1283 | | |
| | | 1284 | | { |
| | 0 | 1285 | | product.Volume = (length * width * height) / 1000000.0; // см³ в литры |
| | | 1286 | | } |
| | | 1287 | | } |
| | | 1288 | | } |
| | | 1289 | | } |
| | | 1290 | | } |
| | | 1291 | | |
| | | 1292 | | |
| | 0 | 1293 | | _context.Products.Add(product); |
| | | 1294 | | |
| | 0 | 1295 | | await _context.SaveChangesAsync(); |
| | | 1296 | | |
| | 0 | 1297 | | order.ProductInfo = product; |
| | | 1298 | | } |
| | 0 | 1299 | | } |
| | | 1300 | | |
| | | 1301 | | |
| | | 1302 | | // Получаем базовую цену из offerMapping для OrderPrice |
| | | 1303 | | |
| | 0 | 1304 | | var basicPriceValue = firstItem["offerMapping"]?["offer"]?["basicPrice"]?["value"]?.ToString(); |
| | | 1305 | | |
| | 0 | 1306 | | var discountBaseValue = firstItem["offerMapping"]?["offer"]?["basicPrice"]?["discountBase"]?.ToString(); |
| | | 1307 | | |
| | | 1308 | | |
| | 0 | 1309 | | decimal? basicPrice = null; |
| | | 1310 | | |
| | 0 | 1311 | | if (!string.IsNullOrEmpty(basicPriceValue)) |
| | | 1312 | | |
| | | 1313 | | { |
| | 0 | 1314 | | if (decimal.TryParse(DelSubStr(basicPriceValue), style, culture, out var parsed)) |
| | | 1315 | | |
| | | 1316 | | { |
| | 0 | 1317 | | basicPrice = parsed; |
| | | 1318 | | } |
| | | 1319 | | } |
| | | 1320 | | |
| | | 1321 | | |
| | 0 | 1322 | | decimal? discountBase = null; |
| | | 1323 | | |
| | 0 | 1324 | | if (!string.IsNullOrEmpty(discountBaseValue)) |
| | | 1325 | | |
| | | 1326 | | { |
| | 0 | 1327 | | if (decimal.TryParse(DelSubStr(discountBaseValue), style, culture, out var parsedBase)) |
| | | 1328 | | |
| | | 1329 | | { |
| | 0 | 1330 | | discountBase = parsedBase; |
| | | 1331 | | } |
| | | 1332 | | } |
| | | 1333 | | |
| | | 1334 | | |
| | | 1335 | | // Расчет итоговых цен |
| | | 1336 | | |
| | 0 | 1337 | | order.ProductInfo.CurrentPriceWithDiscount = basicPrice; |
| | | 1338 | | |
| | | 1339 | | // Цена заказа — реальная цена сделки (оплата покупателя + субсидия Маркета). |
| | | 1340 | | // basicPrice из каталога может быть заглушкой (например, 50000 у скрытого оффера), |
| | | 1341 | | // поэтому он только запасной вариант, если в заказе цены нет. |
| | 0 | 1342 | | order.Price = GetYandexOrderItemPrice(firstItem) ?? basicPrice; |
| | | 1343 | | |
| | 0 | 1344 | | order.ShipmentAmount = order.Price * order.Quantity; |
| | | 1345 | | |
| | | 1346 | | |
| | | 1347 | | // Создаем OrderPrice с безопасными значениями |
| | | 1348 | | |
| | 0 | 1349 | | order.OrderPrice = new OrderPrice |
| | 0 | 1350 | | |
| | 0 | 1351 | | { |
| | 0 | 1352 | | CurrencyCode = firstItem["offerMapping"]?["offer"]?["basicPrice"]?["currencyId"]?.ToString() |
| | 0 | 1353 | | ?? firstItem["prices"]?["payment"]?["currencyId"]?.ToString() |
| | 0 | 1354 | | ?? "RUR" |
| | 0 | 1355 | | }; |
| | | 1356 | | |
| | | 1357 | | |
| | | 1358 | | // Устанавливаем цены только если они есть |
| | | 1359 | | |
| | 0 | 1360 | | if (basicPrice.HasValue) |
| | | 1361 | | |
| | | 1362 | | { |
| | 0 | 1363 | | order.OrderPrice.MarketingPrice = basicPrice.Value; |
| | | 1364 | | |
| | 0 | 1365 | | order.OrderPrice.Price = basicPrice.Value; |
| | | 1366 | | |
| | 0 | 1367 | | order.OrderPrice.RetailPrice = basicPrice.Value; |
| | | 1368 | | } |
| | | 1369 | | |
| | | 1370 | | |
| | 0 | 1371 | | if (discountBase.HasValue) |
| | | 1372 | | |
| | | 1373 | | { |
| | 0 | 1374 | | order.OrderPrice.OldPrice = discountBase.Value; |
| | | 1375 | | } |
| | | 1376 | | |
| | | 1377 | | |
| | | 1378 | | // 11. Исправление: расчет комиссий из tariffs |
| | | 1379 | | |
| | 0 | 1380 | | var tariffsArray = firstItem["tariffs"]; |
| | | 1381 | | |
| | 0 | 1382 | | decimal? totalCommission = 0; |
| | | 1383 | | |
| | | 1384 | | |
| | | 1385 | | // Список допустимых типов комиссий |
| | | 1386 | | |
| | 0 | 1387 | | var allowedCommissionTypes = new HashSet<string> |
| | 0 | 1388 | | |
| | 0 | 1389 | | { |
| | 0 | 1390 | | "AGENCY_COMMISSION", // Прием платежа покупателя |
| | 0 | 1391 | | |
| | 0 | 1392 | | "FEE", // Размещение товара на Маркете |
| | 0 | 1393 | | |
| | 0 | 1394 | | "DELIVERY_TO_CUSTOMER", // Доставка покупателю |
| | 0 | 1395 | | |
| | 0 | 1396 | | "CROSSREGIONAL_DELIVERY", // Доставка в федеральный округ, город или населенный пункт |
| | 0 | 1397 | | |
| | 0 | 1398 | | "EXPRESS_DELIVERY", // Экспресс-доставка покупателю |
| | 0 | 1399 | | |
| | 0 | 1400 | | "MIDDLE_MILE" // Средняя миля |
| | 0 | 1401 | | }; |
| | | 1402 | | |
| | | 1403 | | |
| | 0 | 1404 | | if (tariffsArray != null && tariffsArray.Any()) |
| | | 1405 | | |
| | | 1406 | | { |
| | 0 | 1407 | | decimal sum = 0; |
| | | 1408 | | |
| | 0 | 1409 | | var commissionDetails = new List<string>(); |
| | | 1410 | | |
| | | 1411 | | |
| | | 1412 | | // Используем InvariantCulture для парсинга чисел, чтобы гарантировать работу на любой локали |
| | | 1413 | | |
| | 0 | 1414 | | var invariantCulture = CultureInfo.InvariantCulture; |
| | | 1415 | | |
| | 0 | 1416 | | var numberStyle = NumberStyles.Number | NumberStyles.AllowDecimalPoint; |
| | | 1417 | | |
| | | 1418 | | |
| | 0 | 1419 | | foreach (var tariff in tariffsArray) |
| | | 1420 | | |
| | | 1421 | | { |
| | 0 | 1422 | | var tariffType = tariff?["type"]?.ToString(); |
| | | 1423 | | |
| | 0 | 1424 | | var amountStr = tariff?["amount"]?.ToString(); |
| | | 1425 | | |
| | | 1426 | | |
| | | 1427 | | // Проверяем, что тип комиссии в списке допустимых |
| | | 1428 | | |
| | 0 | 1429 | | if (!string.IsNullOrEmpty(tariffType) && |
| | 0 | 1430 | | allowedCommissionTypes.Contains(tariffType) && |
| | 0 | 1431 | | !string.IsNullOrEmpty(amountStr)) |
| | | 1432 | | |
| | | 1433 | | { |
| | | 1434 | | // Удаляем только апостроф в начале, если есть |
| | | 1435 | | |
| | 0 | 1436 | | var cleanedAmountStr = DelSubStr(amountStr); |
| | | 1437 | | |
| | | 1438 | | |
| | | 1439 | | // Нормализуем десятичный разделитель: заменяем запятую на точку |
| | | 1440 | | |
| | | 1441 | | // Это гарантирует работу на любой локали (ru-RU использует запятую, en-US - точку) |
| | | 1442 | | |
| | 0 | 1443 | | cleanedAmountStr = cleanedAmountStr.Replace(',', '.'); |
| | | 1444 | | |
| | | 1445 | | |
| | | 1446 | | // Парсим с InvariantCulture для гарантии работы на любой локали |
| | | 1447 | | |
| | 0 | 1448 | | if (decimal.TryParse(cleanedAmountStr, numberStyle, invariantCulture, out var amount)) |
| | | 1449 | | |
| | | 1450 | | { |
| | 0 | 1451 | | sum += amount; |
| | | 1452 | | |
| | 0 | 1453 | | commissionDetails.Add($"{tariffType}: {amountStr}"); |
| | | 1454 | | } |
| | | 1455 | | } |
| | | 1456 | | } |
| | | 1457 | | |
| | | 1458 | | |
| | 0 | 1459 | | totalCommission = sum > 0 ? sum + 25 : (decimal?)0; |
| | | 1460 | | |
| | | 1461 | | |
| | | 1462 | | // Сохраняем информацию о комиссиях |
| | | 1463 | | |
| | 0 | 1464 | | if (totalCommission.HasValue && totalCommission.Value > 0) |
| | | 1465 | | |
| | | 1466 | | { |
| | 0 | 1467 | | var commissionInfo = string.Join(", ", commissionDetails); |
| | | 1468 | | |
| | 0 | 1469 | | order.MaxCommissionInfo = commissionInfo; |
| | | 1470 | | |
| | 0 | 1471 | | order.MinCommissionInfo = commissionInfo; |
| | | 1472 | | } |
| | | 1473 | | } |
| | | 1474 | | |
| | | 1475 | | |
| | 0 | 1476 | | order.MaxOzonCommission = totalCommission; |
| | | 1477 | | |
| | 0 | 1478 | | order.MinOzonCommission = totalCommission; |
| | 0 | 1479 | | } |
| | | 1480 | | |
| | | 1481 | | |
| | | 1482 | | // 12. Исправление: город доставки и категория |
| | | 1483 | | |
| | | 1484 | | // Проверяем различные возможные пути к городу доставки |
| | | 1485 | | |
| | 0 | 1486 | | var city = jsonOrder["deliveryRegion"]?["name"]?.ToString() |
| | 0 | 1487 | | ?? jsonOrder["delivery"]?["region"]?["name"]?.ToString() |
| | 0 | 1488 | | ?? jsonOrder["delivery"]?["address"]?["city"]?.ToString() |
| | 0 | 1489 | | ?? string.Empty; |
| | | 1490 | | |
| | 0 | 1491 | | if (!string.IsNullOrEmpty(city)) |
| | | 1492 | | |
| | | 1493 | | { |
| | 0 | 1494 | | order.DeliveryCity = city; |
| | | 1495 | | } |
| | | 1496 | | |
| | | 1497 | | |
| | | 1498 | | // Категория из offerMapping |
| | | 1499 | | |
| | 0 | 1500 | | if (firstItem != null) |
| | | 1501 | | |
| | | 1502 | | { |
| | 0 | 1503 | | var categoryName = firstItem["offerMapping"]?["mapping"]?["marketCategoryName"]?.ToString(); |
| | | 1504 | | |
| | 0 | 1505 | | if (!string.IsNullOrEmpty(categoryName)) |
| | | 1506 | | |
| | | 1507 | | { |
| | 0 | 1508 | | order.NewCategory = categoryName; |
| | | 1509 | | } |
| | | 1510 | | } |
| | | 1511 | | |
| | | 1512 | | |
| | | 1513 | | // 13. Исправление: AppStatus |
| | | 1514 | | |
| | 0 | 1515 | | if (order.AppStatus == null) |
| | | 1516 | | |
| | | 1517 | | { |
| | 0 | 1518 | | string statusName = "Не указан"; |
| | | 1519 | | |
| | | 1520 | | |
| | 0 | 1521 | | var appStatus = _context.AppStatuses.FirstOrDefault(c => c.Name == statusName); |
| | | 1522 | | |
| | | 1523 | | |
| | 0 | 1524 | | if (appStatus != null) |
| | | 1525 | | |
| | | 1526 | | { |
| | 0 | 1527 | | order.AppStatus = appStatus; |
| | | 1528 | | } |
| | | 1529 | | |
| | | 1530 | | else |
| | | 1531 | | |
| | | 1532 | | { |
| | 0 | 1533 | | var newStatus = new AppStatus { Name = statusName }; |
| | | 1534 | | |
| | 0 | 1535 | | _context.AppStatuses.Add(newStatus); |
| | | 1536 | | |
| | 0 | 1537 | | order.AppStatus = newStatus; |
| | | 1538 | | } |
| | | 1539 | | } |
| | | 1540 | | |
| | | 1541 | | |
| | | 1542 | | // 14. Исправление: Supplier |
| | | 1543 | | |
| | 0 | 1544 | | if (order.Supplier == null) |
| | | 1545 | | |
| | | 1546 | | { |
| | 0 | 1547 | | string supplierName = "Не указан"; |
| | | 1548 | | |
| | | 1549 | | |
| | 0 | 1550 | | var supplier = _context.Suppliers.FirstOrDefault(c => c.Name == supplierName); |
| | | 1551 | | |
| | | 1552 | | |
| | 0 | 1553 | | if (supplier != null) |
| | | 1554 | | |
| | | 1555 | | { |
| | 0 | 1556 | | order.Supplier = supplier; |
| | | 1557 | | } |
| | | 1558 | | |
| | | 1559 | | else |
| | | 1560 | | |
| | | 1561 | | { |
| | 0 | 1562 | | var newSupplier = new Supplier { Name = supplierName }; |
| | | 1563 | | |
| | 0 | 1564 | | _context.Suppliers.Add(newSupplier); |
| | | 1565 | | |
| | 0 | 1566 | | order.Supplier = newSupplier; |
| | | 1567 | | } |
| | | 1568 | | } |
| | | 1569 | | |
| | | 1570 | | |
| | 0 | 1571 | | order.UpdatedBy = "Yandex"; |
| | | 1572 | | |
| | 0 | 1573 | | order = SetCorrectProductKey(order); |
| | | 1574 | | |
| | | 1575 | | |
| | 0 | 1576 | | await _context.SaveChangesAsync(); |
| | | 1577 | | |
| | | 1578 | | |
| | 0 | 1579 | | return order; |
| | 0 | 1580 | | } |
| | | 1581 | | |
| | | 1582 | | /// <summary> |
| | | 1583 | | /// Возвращает первое доступное изображение предложения из данных offer-mappings Яндекс.Маркета. |
| | | 1584 | | /// API отдает pictures как массив URL, а в некоторых ответах — как объекты с полем url. |
| | | 1585 | | /// </summary> |
| | | 1586 | | private static string? GetYandexPrimaryImageUrl(JToken? item) |
| | | 1587 | | { |
| | 0 | 1588 | | var offer = item?["offerMapping"]?["offer"]; |
| | | 1589 | | |
| | 0 | 1590 | | foreach (var mediaCollection in new[] { offer?["pictures"], offer?["mediaFiles"] }) |
| | | 1591 | | { |
| | 0 | 1592 | | if (mediaCollection is not JArray mediaItems) |
| | | 1593 | | continue; |
| | | 1594 | | |
| | 0 | 1595 | | foreach (var mediaItem in mediaItems) |
| | | 1596 | | { |
| | 0 | 1597 | | var url = mediaItem.Type == JTokenType.String |
| | 0 | 1598 | | ? mediaItem.Value<string>() |
| | 0 | 1599 | | : mediaItem?["url"]?.Value<string>(); |
| | | 1600 | | |
| | 0 | 1601 | | if (Uri.TryCreate(url, UriKind.Absolute, out var imageUri) && |
| | 0 | 1602 | | (imageUri.Scheme == Uri.UriSchemeHttp || imageUri.Scheme == Uri.UriSchemeHttps)) |
| | | 1603 | | { |
| | 0 | 1604 | | return imageUri.ToString(); |
| | | 1605 | | } |
| | | 1606 | | } |
| | | 1607 | | } |
| | | 1608 | | |
| | 0 | 1609 | | return null; |
| | 0 | 1610 | | } |
| | | 1611 | | |
| | | 1612 | | |
| | | 1613 | | private async Task<Order> CastToModelFromExcel(Dictionary<string, string> dataColumn, |
| | | 1614 | | OzonClient selectedClient, |
| | | 1615 | | Manufacturer selectedManufacturer, |
| | | 1616 | | Warehouse selectedWarehouse, |
| | | 1617 | | Supplier selectedSupplier, |
| | | 1618 | | string selectedClientStatus, |
| | | 1619 | | CurrencyCode selectedCurrencyCode, |
| | | 1620 | | DateTime? selectedShippingDate, |
| | | 1621 | | DateTime? selectedProcessingDate) |
| | | 1622 | | |
| | | 1623 | | { |
| | 0 | 1624 | | Order order = new(); |
| | | 1625 | | |
| | | 1626 | | |
| | 0 | 1627 | | CultureInfo culture = new("en-US"); |
| | | 1628 | | |
| | 0 | 1629 | | NumberStyles style = NumberStyles.Number; |
| | | 1630 | | |
| | | 1631 | | |
| | 0 | 1632 | | if (dataColumn.TryGetValue("Артикул", out var article)) |
| | | 1633 | | |
| | | 1634 | | { |
| | 0 | 1635 | | order.ProductKey = article?.ToString(); |
| | | 1636 | | } |
| | | 1637 | | |
| | 0 | 1638 | | else if (dataColumn.TryGetValue("Key", out var key)) |
| | | 1639 | | |
| | | 1640 | | { |
| | 0 | 1641 | | order.ProductKey = key.ToString(); |
| | | 1642 | | |
| | 0 | 1643 | | article = key.ToString(); |
| | | 1644 | | |
| | 0 | 1645 | | selectedManufacturer = new Manufacturer() { Id = -1 }; |
| | | 1646 | | } |
| | | 1647 | | |
| | | 1648 | | |
| | 0 | 1649 | | order.Key = (dataColumn.TryGetValue("Номер заказа", out var shipmentNumber) |
| | 0 | 1650 | | ? shipmentNumber?.ToString() |
| | 0 | 1651 | | : null) |
| | 0 | 1652 | | + (order.ProductKey != null ? order.ProductKey : null); |
| | | 1653 | | |
| | | 1654 | | |
| | 0 | 1655 | | order.ShipmentNumber = shipmentNumber?.ToString(); |
| | | 1656 | | |
| | | 1657 | | |
| | 0 | 1658 | | if (dataColumn.TryGetValue("Клиент", out var clientName)) |
| | | 1659 | | |
| | | 1660 | | { |
| | 0 | 1661 | | OzonClient clientByName = _context.OzonClients.FirstOrDefault(o => o.Name == clientName); |
| | | 1662 | | |
| | 0 | 1663 | | if (clientByName == null) |
| | | 1664 | | |
| | | 1665 | | { |
| | 0 | 1666 | | OzonClient newOzonClient = new OzonClient() |
| | 0 | 1667 | | |
| | 0 | 1668 | | { |
| | 0 | 1669 | | Name = clientName, |
| | 0 | 1670 | | |
| | 0 | 1671 | | CurrencyCode = CurrencyCode.USD, |
| | 0 | 1672 | | }; |
| | | 1673 | | |
| | | 1674 | | |
| | 0 | 1675 | | _context.OzonClients.Add(newOzonClient); |
| | | 1676 | | |
| | 0 | 1677 | | await _context.SaveChangesAsync(); |
| | | 1678 | | |
| | | 1679 | | |
| | 0 | 1680 | | order.OzonClient = newOzonClient; |
| | 0 | 1681 | | } |
| | | 1682 | | |
| | | 1683 | | else |
| | | 1684 | | |
| | | 1685 | | { |
| | 0 | 1686 | | order.OzonClient = clientByName; |
| | | 1687 | | } |
| | | 1688 | | } |
| | | 1689 | | |
| | 0 | 1690 | | else if (selectedClient.Id != 0) |
| | | 1691 | | |
| | | 1692 | | { |
| | 0 | 1693 | | order.OzonClient = _context.OzonClients.Find(selectedClient.Id); |
| | | 1694 | | } |
| | | 1695 | | |
| | | 1696 | | |
| | 0 | 1697 | | if (selectedCurrencyCode != CurrencyCode.NON && order.OzonClient != null) |
| | | 1698 | | |
| | | 1699 | | { |
| | 0 | 1700 | | if (order.OzonClient.CurrencyCode != selectedCurrencyCode) |
| | | 1701 | | |
| | | 1702 | | { |
| | 0 | 1703 | | order.OzonClient.CurrencyCode = selectedCurrencyCode; |
| | | 1704 | | } |
| | | 1705 | | } |
| | | 1706 | | |
| | 0 | 1707 | | else if (selectedClient.Id != 0) |
| | | 1708 | | |
| | | 1709 | | { |
| | 0 | 1710 | | order.OzonClient = _context.OzonClients.Find(selectedClient.Id); |
| | | 1711 | | } |
| | | 1712 | | |
| | | 1713 | | |
| | 0 | 1714 | | var cultureDateInfo = new CultureInfo("ru-RU"); |
| | | 1715 | | |
| | | 1716 | | |
| | 0 | 1717 | | order.ProcessingDate = dataColumn.TryGetValue("Принят в обработку", out var processingDateStr) && |
| | 0 | 1718 | | DateTime.TryParse(processingDateStr, cultureDateInfo, DateTimeStyles.None, |
| | 0 | 1719 | | out var processingDate) |
| | 0 | 1720 | | ? processingDate |
| | 0 | 1721 | | : selectedProcessingDate != null |
| | 0 | 1722 | | ? selectedProcessingDate |
| | 0 | 1723 | | : DateTime.Now.AddHours(_releaseManager.GetTimeZone()); |
| | | 1724 | | |
| | | 1725 | | |
| | 0 | 1726 | | order.ShippingDate = dataColumn.TryGetValue("Дата отгрузки", out var shippingDateStr) && |
| | 0 | 1727 | | DateTime.TryParse(shippingDateStr, cultureDateInfo, DateTimeStyles.None, |
| | 0 | 1728 | | out var shippingDate) |
| | 0 | 1729 | | ? shippingDate |
| | 0 | 1730 | | : selectedShippingDate; |
| | | 1731 | | |
| | | 1732 | | |
| | | 1733 | | // Проверяем "Статус клиента" сначала, затем "Статус" |
| | | 1734 | | |
| | 0 | 1735 | | if (dataColumn.TryGetValue("Статус клиента", out var clientStatusValue)) |
| | | 1736 | | |
| | | 1737 | | { |
| | 0 | 1738 | | order.ClientStatus = await GetOrCreateClientStatusAsync(clientStatusValue?.ToString()); |
| | | 1739 | | } |
| | | 1740 | | |
| | 0 | 1741 | | else if (dataColumn.TryGetValue("Статус", out var status)) |
| | | 1742 | | |
| | | 1743 | | { |
| | 0 | 1744 | | order.ClientStatus = await GetOrCreateClientStatusAsync(status?.ToString()); |
| | | 1745 | | } |
| | | 1746 | | |
| | 0 | 1747 | | else if (selectedClientStatus != null) |
| | | 1748 | | |
| | | 1749 | | { |
| | 0 | 1750 | | order.ClientStatus = await GetOrCreateClientStatusAsync(selectedClientStatus); |
| | | 1751 | | } |
| | | 1752 | | |
| | | 1753 | | else |
| | | 1754 | | |
| | | 1755 | | { |
| | 0 | 1756 | | order.ClientStatus = null; |
| | | 1757 | | } |
| | | 1758 | | |
| | | 1759 | | |
| | 0 | 1760 | | order.ProductName = dataColumn.TryGetValue("Наименование товара", out var productName) |
| | 0 | 1761 | | ? productName?.ToString() |
| | 0 | 1762 | | : null; |
| | | 1763 | | |
| | | 1764 | | |
| | 0 | 1765 | | order.Quantity = dataColumn.TryGetValue("Кол.", out var quantityStr) && |
| | 0 | 1766 | | int.TryParse(DelSubStr(quantityStr), style, culture, out var quantity) |
| | 0 | 1767 | | ? quantity |
| | 0 | 1768 | | : (int?)null; |
| | | 1769 | | |
| | | 1770 | | |
| | 0 | 1771 | | if (dataColumn.TryGetValue("Склад отгрузки", out var warehouseName)) |
| | | 1772 | | |
| | | 1773 | | { |
| | 0 | 1774 | | Warehouse shipmentWarehouse = _context.Warehouses.FirstOrDefault(w => w.Name == warehouseName); |
| | | 1775 | | |
| | | 1776 | | |
| | 0 | 1777 | | if (shipmentWarehouse != null) |
| | | 1778 | | |
| | | 1779 | | { |
| | 0 | 1780 | | order.ShipmentWarehouse = shipmentWarehouse; |
| | | 1781 | | } |
| | | 1782 | | |
| | | 1783 | | else |
| | | 1784 | | |
| | | 1785 | | { |
| | 0 | 1786 | | var newWarehouse = new Warehouse { Name = warehouseName }; |
| | | 1787 | | |
| | 0 | 1788 | | _context.Warehouses.Add(newWarehouse); |
| | | 1789 | | |
| | 0 | 1790 | | await _context.SaveChangesAsync(); |
| | | 1791 | | |
| | 0 | 1792 | | order.ShipmentWarehouse = newWarehouse; |
| | 0 | 1793 | | } |
| | | 1794 | | } |
| | | 1795 | | |
| | 0 | 1796 | | else if (selectedWarehouse != null && selectedWarehouse.Id != 0) |
| | | 1797 | | |
| | | 1798 | | { |
| | 0 | 1799 | | order.ShipmentWarehouse = _context.Warehouses.FirstOrDefault(w => w.Id == selectedWarehouse.Id); |
| | | 1800 | | } |
| | | 1801 | | |
| | | 1802 | | |
| | 0 | 1803 | | if (dataColumn.TryGetValue("Производитель", out var manufacturerName)) |
| | | 1804 | | |
| | | 1805 | | { |
| | 0 | 1806 | | Manufacturer manufacturer = _context.Manufacturers.FirstOrDefault(m => m.Name == manufacturerName); |
| | | 1807 | | |
| | | 1808 | | |
| | 0 | 1809 | | if (manufacturer != null) |
| | | 1810 | | |
| | | 1811 | | { |
| | 0 | 1812 | | order.Manufacturer = manufacturer; |
| | | 1813 | | } |
| | | 1814 | | |
| | | 1815 | | else |
| | | 1816 | | |
| | | 1817 | | { |
| | 0 | 1818 | | var newManufacturer = new Manufacturer |
| | 0 | 1819 | | |
| | 0 | 1820 | | { |
| | 0 | 1821 | | Code = null, |
| | 0 | 1822 | | |
| | 0 | 1823 | | Name = manufacturerName |
| | 0 | 1824 | | }; |
| | | 1825 | | |
| | | 1826 | | |
| | 0 | 1827 | | _context.Manufacturers.Add(newManufacturer); |
| | | 1828 | | |
| | 0 | 1829 | | _context.SaveChanges(); |
| | | 1830 | | |
| | | 1831 | | |
| | 0 | 1832 | | order.Manufacturer = newManufacturer; |
| | | 1833 | | } |
| | | 1834 | | |
| | | 1835 | | |
| | 0 | 1836 | | order = await SetEtProducerByName(order, manufacturerName); |
| | | 1837 | | } |
| | | 1838 | | |
| | 0 | 1839 | | else if (selectedManufacturer != null && selectedManufacturer.Id != 0) |
| | | 1840 | | |
| | | 1841 | | { |
| | 0 | 1842 | | if (selectedManufacturer.Id == -1) |
| | | 1843 | | |
| | | 1844 | | { |
| | 0 | 1845 | | string extractedCode = Regex.Match(article.ToString(), @"=(\w{3})").Groups[1].Value; |
| | | 1846 | | |
| | | 1847 | | |
| | 0 | 1848 | | if (string.IsNullOrEmpty(extractedCode)) |
| | | 1849 | | |
| | | 1850 | | { |
| | 0 | 1851 | | extractedCode = Regex.Match(article.ToString(), @"=(\w{2})").Groups[1].Value; |
| | | 1852 | | } |
| | | 1853 | | |
| | | 1854 | | |
| | 0 | 1855 | | Manufacturer manufacturer = _context.Manufacturers |
| | 0 | 1856 | | .Where(m => m.Code == extractedCode) |
| | 0 | 1857 | | .FirstOrDefault(); |
| | | 1858 | | |
| | | 1859 | | |
| | 0 | 1860 | | if (manufacturer != null) |
| | | 1861 | | |
| | | 1862 | | { |
| | 0 | 1863 | | order.Manufacturer = manufacturer; |
| | | 1864 | | } |
| | | 1865 | | |
| | | 1866 | | else |
| | | 1867 | | |
| | | 1868 | | { |
| | 0 | 1869 | | var newManufacturer = new Manufacturer { Code = extractedCode }; |
| | | 1870 | | |
| | 0 | 1871 | | _context.Manufacturers.Add(newManufacturer); |
| | | 1872 | | |
| | 0 | 1873 | | _context.SaveChanges(); |
| | | 1874 | | |
| | 0 | 1875 | | order.Manufacturer = newManufacturer; |
| | | 1876 | | } |
| | | 1877 | | |
| | | 1878 | | |
| | 0 | 1879 | | order = await SetEtProducerByCode(order, extractedCode); |
| | | 1880 | | } |
| | | 1881 | | |
| | 0 | 1882 | | else if (selectedManufacturer.Id == -2) |
| | | 1883 | | |
| | | 1884 | | { |
| | 0 | 1885 | | string tabelManufacturerName = order.ProductName != null ? order.ProductName.Split(' ')[0] : null; |
| | | 1886 | | |
| | 0 | 1887 | | if (tabelManufacturerName != null) |
| | | 1888 | | |
| | | 1889 | | { |
| | 0 | 1890 | | Manufacturer manufacturer = _context.Manufacturers |
| | 0 | 1891 | | .Where(m => m.Name.ToLower().Contains(tabelManufacturerName.ToLower())).FirstOrDefault(); |
| | | 1892 | | |
| | 0 | 1893 | | if (manufacturer != null) |
| | | 1894 | | |
| | | 1895 | | { |
| | 0 | 1896 | | order.Manufacturer = manufacturer; |
| | | 1897 | | } |
| | | 1898 | | } |
| | | 1899 | | } |
| | | 1900 | | |
| | | 1901 | | else |
| | | 1902 | | |
| | | 1903 | | { |
| | 0 | 1904 | | order.Manufacturer = _context.Manufacturers.FirstOrDefault(m => m.Id == selectedManufacturer.Id); |
| | | 1905 | | } |
| | | 1906 | | } |
| | | 1907 | | |
| | | 1908 | | |
| | 0 | 1909 | | if (dataColumn.TryGetValue("Код валюты отправления", out var currencyName)) |
| | | 1910 | | |
| | | 1911 | | { |
| | 0 | 1912 | | Currency currency = _context.Currencys.FirstOrDefault(c => c.Name == currencyName); |
| | | 1913 | | |
| | | 1914 | | |
| | 0 | 1915 | | if (currency != null) |
| | | 1916 | | |
| | | 1917 | | { |
| | 0 | 1918 | | order.Сurrency = currency; |
| | | 1919 | | } |
| | | 1920 | | |
| | | 1921 | | else |
| | | 1922 | | |
| | | 1923 | | { |
| | 0 | 1924 | | var newCurrency = new Currency |
| | 0 | 1925 | | |
| | 0 | 1926 | | { |
| | 0 | 1927 | | Name = currencyName |
| | 0 | 1928 | | }; |
| | | 1929 | | |
| | | 1930 | | |
| | 0 | 1931 | | _context.Currencys.Add(newCurrency); |
| | | 1932 | | |
| | 0 | 1933 | | await _context.SaveChangesAsync(); |
| | | 1934 | | |
| | 0 | 1935 | | order.Сurrency = newCurrency; |
| | 0 | 1936 | | } |
| | | 1937 | | } |
| | | 1938 | | |
| | | 1939 | | |
| | 0 | 1940 | | order.Supplier = null; |
| | | 1941 | | |
| | 0 | 1942 | | order.PurchasePrice = null; |
| | | 1943 | | |
| | | 1944 | | |
| | 0 | 1945 | | if (order.ProductInfo == null && dataColumn.TryGetValue("Артикул", out var productArticle)) |
| | | 1946 | | |
| | | 1947 | | { |
| | 0 | 1948 | | Product product = _context.Products.FirstOrDefault(p => p.Article == productArticle); |
| | | 1949 | | |
| | | 1950 | | |
| | 0 | 1951 | | if (product != null) |
| | | 1952 | | |
| | | 1953 | | { |
| | 0 | 1954 | | order.ProductInfo = product; |
| | | 1955 | | } |
| | | 1956 | | |
| | | 1957 | | else |
| | | 1958 | | |
| | | 1959 | | { |
| | 0 | 1960 | | product = new Product |
| | 0 | 1961 | | |
| | 0 | 1962 | | { |
| | 0 | 1963 | | Article = productArticle |
| | 0 | 1964 | | }; |
| | | 1965 | | |
| | | 1966 | | |
| | 0 | 1967 | | _context.Products.Add(product); |
| | | 1968 | | |
| | 0 | 1969 | | await _context.SaveChangesAsync(); |
| | | 1970 | | |
| | 0 | 1971 | | order.ProductInfo = product; |
| | | 1972 | | } |
| | 0 | 1973 | | } |
| | | 1974 | | |
| | 0 | 1975 | | else if (order.ProductInfo == null && !dataColumn.TryGetValue("Артикул", out var nullProductArticle)) |
| | | 1976 | | |
| | | 1977 | | { |
| | 0 | 1978 | | var product = new Product(); |
| | | 1979 | | |
| | | 1980 | | |
| | 0 | 1981 | | _context.Products.Add(product); |
| | | 1982 | | |
| | 0 | 1983 | | _context.SaveChanges(); |
| | | 1984 | | |
| | | 1985 | | |
| | 0 | 1986 | | order.ProductInfo = product; |
| | | 1987 | | } |
| | | 1988 | | |
| | | 1989 | | |
| | 0 | 1990 | | order.DeliveryCity = dataColumn.TryGetValue("Город доставки", out var deliveryCity) |
| | 0 | 1991 | | ? deliveryCity?.ToString() |
| | 0 | 1992 | | : null; |
| | | 1993 | | |
| | | 1994 | | |
| | | 1995 | | // Проверяем "Статус клиента" сначала, затем "Статус клинта" (для обратной совместимости), затем "Статус" |
| | | 1996 | | |
| | 0 | 1997 | | string clientStatusValue1 = null; |
| | | 1998 | | |
| | 0 | 1999 | | if (dataColumn.TryGetValue("Статус клиента", out clientStatusValue1)) |
| | | 2000 | | |
| | | 2001 | | { |
| | 0 | 2002 | | order.ClientStatus = await GetOrCreateClientStatusAsync(clientStatusValue1?.ToString()); |
| | | 2003 | | } |
| | | 2004 | | |
| | 0 | 2005 | | else if (dataColumn.TryGetValue("Статус клинта", out var clientStauts)) |
| | | 2006 | | |
| | | 2007 | | { |
| | 0 | 2008 | | order.ClientStatus = await GetOrCreateClientStatusAsync(clientStauts?.ToString()); |
| | | 2009 | | } |
| | | 2010 | | |
| | 0 | 2011 | | else if (dataColumn.TryGetValue("Статус", out var status)) |
| | | 2012 | | |
| | | 2013 | | { |
| | 0 | 2014 | | order.ClientStatus = await GetOrCreateClientStatusAsync(status?.ToString()); |
| | | 2015 | | } |
| | | 2016 | | |
| | 0 | 2017 | | else if (selectedClientStatus != null) |
| | | 2018 | | |
| | | 2019 | | { |
| | 0 | 2020 | | order.ClientStatus = await GetOrCreateClientStatusAsync(selectedClientStatus); |
| | | 2021 | | } |
| | | 2022 | | |
| | | 2023 | | else |
| | | 2024 | | |
| | | 2025 | | { |
| | 0 | 2026 | | order.ClientStatus = null; |
| | | 2027 | | } |
| | | 2028 | | |
| | | 2029 | | |
| | 0 | 2030 | | if (order.AppStatus == null) |
| | | 2031 | | |
| | | 2032 | | { |
| | 0 | 2033 | | string statusName = "Не указан"; |
| | | 2034 | | |
| | | 2035 | | |
| | 0 | 2036 | | AppStatus appStatus = _context.AppStatuses.FirstOrDefault(c => c.Name == statusName); |
| | | 2037 | | |
| | | 2038 | | |
| | 0 | 2039 | | if (appStatus != null) |
| | | 2040 | | |
| | | 2041 | | { |
| | 0 | 2042 | | order.AppStatus = appStatus; |
| | | 2043 | | } |
| | | 2044 | | |
| | | 2045 | | else |
| | | 2046 | | |
| | | 2047 | | { |
| | 0 | 2048 | | var newStatus = new AppStatus { Name = statusName }; |
| | | 2049 | | |
| | | 2050 | | |
| | 0 | 2051 | | _context.AppStatuses.Add(newStatus); |
| | | 2052 | | |
| | 0 | 2053 | | await _context.SaveChangesAsync(); |
| | | 2054 | | |
| | 0 | 2055 | | order.AppStatus = newStatus; |
| | 0 | 2056 | | } |
| | | 2057 | | } |
| | | 2058 | | |
| | | 2059 | | |
| | 0 | 2060 | | if (order.Supplier == null && selectedSupplier.Id == 0) |
| | | 2061 | | |
| | | 2062 | | { |
| | 0 | 2063 | | string supplierName = "Не указан"; |
| | | 2064 | | |
| | | 2065 | | |
| | 0 | 2066 | | Supplier supplier = _context.Suppliers.FirstOrDefault(c => c.Name == supplierName); |
| | | 2067 | | |
| | | 2068 | | |
| | 0 | 2069 | | if (supplier != null) |
| | | 2070 | | |
| | | 2071 | | { |
| | 0 | 2072 | | order.Supplier = supplier; |
| | | 2073 | | } |
| | | 2074 | | |
| | | 2075 | | else |
| | | 2076 | | |
| | | 2077 | | { |
| | 0 | 2078 | | var newSupplier = new Supplier { Name = supplierName }; |
| | | 2079 | | |
| | | 2080 | | |
| | 0 | 2081 | | _context.Suppliers.Add(newSupplier); |
| | | 2082 | | |
| | 0 | 2083 | | await _context.SaveChangesAsync(); |
| | | 2084 | | |
| | 0 | 2085 | | order.Supplier = newSupplier; |
| | 0 | 2086 | | } |
| | | 2087 | | } |
| | | 2088 | | |
| | 0 | 2089 | | else if (selectedSupplier.Id != 0) |
| | | 2090 | | |
| | | 2091 | | { |
| | 0 | 2092 | | order.Supplier = _context.Suppliers.FirstOrDefault(m => m.Id == selectedSupplier.Id); |
| | | 2093 | | } |
| | | 2094 | | |
| | | 2095 | | |
| | 0 | 2096 | | order.Price = dataColumn.TryGetValue("Цена", out var priceStr) && |
| | 0 | 2097 | | decimal.TryParse(DelSubStr(priceStr), style, culture, out var price) |
| | 0 | 2098 | | ? price |
| | 0 | 2099 | | : (decimal?)null; |
| | | 2100 | | |
| | | 2101 | | |
| | 0 | 2102 | | if (dataColumn.TryGetValue("Сумма отправления", out var shipmentAmountStr) && |
| | 0 | 2103 | | decimal.TryParse(DelSubStr(shipmentAmountStr), style, culture, out var shipmentAmount)) |
| | | 2104 | | |
| | | 2105 | | { |
| | 0 | 2106 | | order.ShipmentAmount = shipmentAmount; |
| | | 2107 | | } |
| | | 2108 | | |
| | 0 | 2109 | | else if (order.Price != (decimal?)null && order.Quantity != (int?)null) |
| | | 2110 | | |
| | | 2111 | | { |
| | 0 | 2112 | | order.ShipmentAmount = order.Price * order.Quantity; |
| | | 2113 | | } |
| | | 2114 | | |
| | | 2115 | | |
| | | 2116 | | // Если в файле нет колонки «Цена сайта» (или она пустая), базой расчёта служит «Цена». |
| | 0 | 2117 | | order.ProductInfo.CurrentPriceWithDiscount = |
| | 0 | 2118 | | dataColumn.TryGetValue("Цена сайта", out var priceWithDiscountStr) && |
| | 0 | 2119 | | decimal.TryParse(priceWithDiscountStr, style, culture, out var priceWithDiscount) && |
| | 0 | 2120 | | priceWithDiscount > 0 |
| | 0 | 2121 | | ? priceWithDiscount |
| | 0 | 2122 | | : order.Price ?? 0; |
| | | 2123 | | |
| | | 2124 | | |
| | 0 | 2125 | | order.MaxOzonCommission = dataColumn.TryGetValue("Максимальная комиссия", out var maxOzonCommissionStr) && |
| | 0 | 2126 | | decimal.TryParse(maxOzonCommissionStr, style, culture, out var maxOzonCommission) |
| | 0 | 2127 | | ? maxOzonCommission |
| | 0 | 2128 | | : 0; |
| | | 2129 | | |
| | | 2130 | | |
| | 0 | 2131 | | order.MinOzonCommission = dataColumn.TryGetValue("Минимальная комиссия", out var minOzonCommissionStr) && |
| | 0 | 2132 | | decimal.TryParse(minOzonCommissionStr, style, culture, out var minOzonCommission) |
| | 0 | 2133 | | ? minOzonCommission |
| | 0 | 2134 | | : 0; |
| | | 2135 | | |
| | | 2136 | | |
| | 0 | 2137 | | order.PurchasePrice = dataColumn.TryGetValue("Цена закупки", out var purchasePriceStr) && |
| | 0 | 2138 | | decimal.TryParse(purchasePriceStr, style, culture, out var purchasePrice) |
| | 0 | 2139 | | ? purchasePrice |
| | 0 | 2140 | | : 0; |
| | | 2141 | | |
| | | 2142 | | |
| | 0 | 2143 | | order = SetCorrectProductKey(order); |
| | | 2144 | | |
| | | 2145 | | |
| | 0 | 2146 | | order.FromFile = true; |
| | | 2147 | | |
| | 0 | 2148 | | order.UpdatedBy = "Excel"; |
| | | 2149 | | |
| | | 2150 | | |
| | 0 | 2151 | | _context.SaveChanges(); |
| | | 2152 | | |
| | | 2153 | | |
| | 0 | 2154 | | order = await _ordersDataServices.CastToModel(order); |
| | | 2155 | | |
| | | 2156 | | |
| | 0 | 2157 | | return order; |
| | 0 | 2158 | | } |
| | | 2159 | | |
| | | 2160 | | |
| | | 2161 | | private async Task<Order> CastToModelFromExcelForDropBox(Dictionary<string, string> dataColumn, |
| | | 2162 | | OzonClient selectedClient, |
| | | 2163 | | Manufacturer selectedManufacturer, |
| | | 2164 | | Warehouse selectedWarehouse, |
| | | 2165 | | Supplier selectedSupplier, |
| | | 2166 | | string selectedClientStatus, |
| | | 2167 | | CurrencyCode selectedCurrencyCode, |
| | | 2168 | | DateTime? selectedShippingDate, |
| | | 2169 | | DateTime? selectedProcessingDate, |
| | | 2170 | | string deliveryName) |
| | | 2171 | | |
| | | 2172 | | { |
| | 0 | 2173 | | Order order = new(); |
| | | 2174 | | |
| | | 2175 | | |
| | 0 | 2176 | | CultureInfo culture = new("en-US"); |
| | | 2177 | | |
| | 0 | 2178 | | NumberStyles style = NumberStyles.Number; |
| | | 2179 | | |
| | 0 | 2180 | | string regionCode = _releaseManager.GetRegionCode(); |
| | | 2181 | | |
| | | 2182 | | |
| | 0 | 2183 | | if (dataColumn.TryGetValue("Артикул", out var article)) |
| | | 2184 | | |
| | | 2185 | | { |
| | 0 | 2186 | | order.ProductKey = article?.ToString(); |
| | | 2187 | | } |
| | | 2188 | | |
| | 0 | 2189 | | else if (dataColumn.TryGetValue("Key", out var key)) |
| | | 2190 | | |
| | | 2191 | | { |
| | 0 | 2192 | | order.ProductKey = key.ToString(); |
| | | 2193 | | |
| | 0 | 2194 | | article = key.ToString(); |
| | | 2195 | | |
| | 0 | 2196 | | selectedManufacturer = new Manufacturer() { Id = -1 }; |
| | | 2197 | | } |
| | | 2198 | | |
| | | 2199 | | |
| | 0 | 2200 | | order.Key = (dataColumn.TryGetValue("Номер заказа", out var shipmentNumber) |
| | 0 | 2201 | | ? shipmentNumber?.ToString() |
| | 0 | 2202 | | : null) |
| | 0 | 2203 | | + (order.ProductKey != null ? order.ProductKey : null); |
| | | 2204 | | |
| | | 2205 | | |
| | 0 | 2206 | | order.ShipmentNumber = shipmentNumber?.ToString(); |
| | | 2207 | | |
| | | 2208 | | |
| | 0 | 2209 | | if (dataColumn.TryGetValue("Клиент", out var clientName)) |
| | | 2210 | | |
| | | 2211 | | { |
| | 0 | 2212 | | OzonClient clientByName = _context.OzonClients.FirstOrDefault(o => o.Name == clientName); |
| | | 2213 | | |
| | 0 | 2214 | | if (clientByName == null) |
| | | 2215 | | |
| | | 2216 | | { |
| | 0 | 2217 | | OzonClient newOzonClient = new OzonClient() |
| | 0 | 2218 | | |
| | 0 | 2219 | | { |
| | 0 | 2220 | | Name = clientName, |
| | 0 | 2221 | | |
| | 0 | 2222 | | CurrencyCode = CurrencyCode.USD, |
| | 0 | 2223 | | }; |
| | | 2224 | | |
| | | 2225 | | |
| | 0 | 2226 | | _context.OzonClients.Add(newOzonClient); |
| | | 2227 | | |
| | 0 | 2228 | | await _context.SaveChangesAsync(); |
| | | 2229 | | |
| | | 2230 | | |
| | 0 | 2231 | | order.OzonClient = newOzonClient; |
| | 0 | 2232 | | } |
| | | 2233 | | |
| | | 2234 | | else |
| | | 2235 | | |
| | | 2236 | | { |
| | 0 | 2237 | | order.OzonClient = clientByName; |
| | | 2238 | | } |
| | | 2239 | | } |
| | | 2240 | | |
| | 0 | 2241 | | else if (selectedClient.Id != 0) |
| | | 2242 | | |
| | | 2243 | | { |
| | 0 | 2244 | | order.OzonClient = _context.OzonClients.Find(selectedClient.Id); |
| | | 2245 | | } |
| | | 2246 | | |
| | | 2247 | | |
| | 0 | 2248 | | if (selectedCurrencyCode != CurrencyCode.NON && order.OzonClient != null) |
| | | 2249 | | |
| | | 2250 | | { |
| | 0 | 2251 | | if (order.OzonClient.CurrencyCode != selectedCurrencyCode) |
| | | 2252 | | |
| | | 2253 | | { |
| | 0 | 2254 | | order.OzonClient.CurrencyCode = selectedCurrencyCode; |
| | | 2255 | | } |
| | | 2256 | | } |
| | | 2257 | | |
| | 0 | 2258 | | else if (selectedClient.Id != 0) |
| | | 2259 | | |
| | | 2260 | | { |
| | 0 | 2261 | | order.OzonClient = _context.OzonClients.Find(selectedClient.Id); |
| | | 2262 | | } |
| | | 2263 | | |
| | | 2264 | | |
| | 0 | 2265 | | var cultureDateInfo = new CultureInfo("ru-RU"); |
| | | 2266 | | |
| | | 2267 | | |
| | 0 | 2268 | | order.ProcessingDate = dataColumn.TryGetValue("Принят в обработку", out var processingDateStr) && |
| | 0 | 2269 | | DateTime.TryParse(processingDateStr, cultureDateInfo, DateTimeStyles.None, |
| | 0 | 2270 | | out var processingDate) |
| | 0 | 2271 | | ? processingDate |
| | 0 | 2272 | | : selectedProcessingDate != null |
| | 0 | 2273 | | ? selectedProcessingDate |
| | 0 | 2274 | | : DateTime.Now.AddHours(_releaseManager.GetTimeZone()); |
| | | 2275 | | |
| | | 2276 | | |
| | 0 | 2277 | | order.ShippingDate = dataColumn.TryGetValue("Дата отгрузки", out var shippingDateStr) && |
| | 0 | 2278 | | DateTime.TryParse(shippingDateStr, cultureDateInfo, DateTimeStyles.None, |
| | 0 | 2279 | | out var shippingDate) |
| | 0 | 2280 | | ? shippingDate |
| | 0 | 2281 | | : selectedShippingDate; |
| | | 2282 | | |
| | | 2283 | | |
| | | 2284 | | // Проверяем "Статус клиента" сначала, затем "Статус" |
| | | 2285 | | |
| | 0 | 2286 | | if (dataColumn.TryGetValue("Статус клиента", out var clientStatusValue)) |
| | | 2287 | | |
| | | 2288 | | { |
| | 0 | 2289 | | order.ClientStatus = await GetOrCreateClientStatusAsync(clientStatusValue?.ToString()); |
| | | 2290 | | } |
| | | 2291 | | |
| | 0 | 2292 | | else if (dataColumn.TryGetValue("Статус", out var status)) |
| | | 2293 | | |
| | | 2294 | | { |
| | 0 | 2295 | | order.ClientStatus = await GetOrCreateClientStatusAsync(status?.ToString()); |
| | | 2296 | | } |
| | | 2297 | | |
| | 0 | 2298 | | else if (selectedClientStatus != null) |
| | | 2299 | | |
| | | 2300 | | { |
| | 0 | 2301 | | order.ClientStatus = await GetOrCreateClientStatusAsync(selectedClientStatus); |
| | | 2302 | | } |
| | | 2303 | | |
| | | 2304 | | else |
| | | 2305 | | |
| | | 2306 | | { |
| | 0 | 2307 | | order.ClientStatus = null; |
| | | 2308 | | } |
| | | 2309 | | |
| | | 2310 | | |
| | 0 | 2311 | | order.ProductName = dataColumn.TryGetValue("Наименование товара", out var productName) |
| | 0 | 2312 | | ? productName?.ToString() |
| | 0 | 2313 | | : null; |
| | | 2314 | | |
| | | 2315 | | |
| | 0 | 2316 | | order.Quantity = dataColumn.TryGetValue("Кол.", out var quantityStr) && |
| | 0 | 2317 | | int.TryParse(DelSubStr(quantityStr), style, culture, out var quantity) |
| | 0 | 2318 | | ? quantity |
| | 0 | 2319 | | : (int?)null; |
| | | 2320 | | |
| | | 2321 | | |
| | 0 | 2322 | | if (dataColumn.TryGetValue("Склад отгрузки", out var warehouseName)) |
| | | 2323 | | |
| | | 2324 | | { |
| | 0 | 2325 | | Warehouse shipmentWarehouse = _context.Warehouses.FirstOrDefault(w => w.Name == warehouseName); |
| | | 2326 | | |
| | | 2327 | | |
| | 0 | 2328 | | if (shipmentWarehouse != null) |
| | | 2329 | | |
| | | 2330 | | { |
| | 0 | 2331 | | order.ShipmentWarehouse = shipmentWarehouse; |
| | | 2332 | | } |
| | | 2333 | | |
| | | 2334 | | else |
| | | 2335 | | |
| | | 2336 | | { |
| | 0 | 2337 | | var newWarehouse = new Warehouse { Name = warehouseName }; |
| | | 2338 | | |
| | 0 | 2339 | | _context.Warehouses.Add(newWarehouse); |
| | | 2340 | | |
| | 0 | 2341 | | await _context.SaveChangesAsync(); |
| | | 2342 | | |
| | 0 | 2343 | | order.ShipmentWarehouse = newWarehouse; |
| | 0 | 2344 | | } |
| | | 2345 | | } |
| | | 2346 | | |
| | 0 | 2347 | | else if (selectedWarehouse != null && selectedWarehouse.Id != 0) |
| | | 2348 | | |
| | | 2349 | | { |
| | 0 | 2350 | | order.ShipmentWarehouse = _context.Warehouses.FirstOrDefault(w => w.Id == selectedWarehouse.Id); |
| | | 2351 | | } |
| | | 2352 | | |
| | | 2353 | | |
| | 0 | 2354 | | if (dataColumn.TryGetValue("Производитель", out var manufacturerName)) |
| | | 2355 | | |
| | | 2356 | | { |
| | 0 | 2357 | | Manufacturer manufacturer = _context.Manufacturers.FirstOrDefault(m => m.Name == manufacturerName); |
| | | 2358 | | |
| | | 2359 | | |
| | 0 | 2360 | | if (manufacturer != null) |
| | | 2361 | | |
| | | 2362 | | { |
| | 0 | 2363 | | order.Manufacturer = manufacturer; |
| | | 2364 | | } |
| | | 2365 | | |
| | | 2366 | | else |
| | | 2367 | | |
| | | 2368 | | { |
| | 0 | 2369 | | var newManufacturer = new Manufacturer |
| | 0 | 2370 | | |
| | 0 | 2371 | | { |
| | 0 | 2372 | | Code = null, |
| | 0 | 2373 | | |
| | 0 | 2374 | | Name = manufacturerName |
| | 0 | 2375 | | }; |
| | | 2376 | | |
| | | 2377 | | |
| | 0 | 2378 | | _context.Manufacturers.Add(newManufacturer); |
| | | 2379 | | |
| | 0 | 2380 | | _context.SaveChanges(); |
| | | 2381 | | |
| | | 2382 | | |
| | 0 | 2383 | | order.Manufacturer = newManufacturer; |
| | | 2384 | | } |
| | | 2385 | | |
| | | 2386 | | |
| | 0 | 2387 | | order = await SetEtProducerByName(order, manufacturerName); |
| | | 2388 | | } |
| | | 2389 | | |
| | 0 | 2390 | | else if (selectedManufacturer != null && selectedManufacturer.Id != 0) |
| | | 2391 | | |
| | | 2392 | | { |
| | 0 | 2393 | | if (selectedManufacturer.Id == -1) |
| | | 2394 | | |
| | | 2395 | | { |
| | 0 | 2396 | | string extractedCode = Regex.Match(article.ToString(), @"=(\w{3})").Groups[1].Value; |
| | | 2397 | | |
| | | 2398 | | |
| | 0 | 2399 | | if (string.IsNullOrEmpty(extractedCode)) |
| | | 2400 | | |
| | | 2401 | | { |
| | 0 | 2402 | | extractedCode = Regex.Match(article.ToString(), @"=(\w{2})").Groups[1].Value; |
| | | 2403 | | } |
| | | 2404 | | |
| | | 2405 | | |
| | 0 | 2406 | | Manufacturer manufacturer = _context.Manufacturers |
| | 0 | 2407 | | .Where(m => m.Code == extractedCode) |
| | 0 | 2408 | | .FirstOrDefault(); |
| | | 2409 | | |
| | | 2410 | | |
| | 0 | 2411 | | if (manufacturer != null) |
| | | 2412 | | |
| | | 2413 | | { |
| | 0 | 2414 | | order.Manufacturer = manufacturer; |
| | | 2415 | | } |
| | | 2416 | | |
| | | 2417 | | else |
| | | 2418 | | |
| | | 2419 | | { |
| | 0 | 2420 | | var newManufacturer = new Manufacturer { Code = extractedCode }; |
| | | 2421 | | |
| | 0 | 2422 | | _context.Manufacturers.Add(newManufacturer); |
| | | 2423 | | |
| | 0 | 2424 | | _context.SaveChanges(); |
| | | 2425 | | |
| | 0 | 2426 | | order.Manufacturer = newManufacturer; |
| | | 2427 | | } |
| | | 2428 | | |
| | | 2429 | | |
| | 0 | 2430 | | order = await SetEtProducerByCode(order, extractedCode); |
| | | 2431 | | } |
| | | 2432 | | |
| | 0 | 2433 | | else if (selectedManufacturer.Id == -2) |
| | | 2434 | | |
| | | 2435 | | { |
| | 0 | 2436 | | string tabelManufacturerName = order.ProductName != null ? order.ProductName.Split(' ')[0] : null; |
| | | 2437 | | |
| | 0 | 2438 | | if (tabelManufacturerName != null) |
| | | 2439 | | |
| | | 2440 | | { |
| | 0 | 2441 | | Manufacturer manufacturer = _context.Manufacturers |
| | 0 | 2442 | | .Where(m => m.Name.ToLower().Contains(tabelManufacturerName.ToLower())).FirstOrDefault(); |
| | | 2443 | | |
| | 0 | 2444 | | if (manufacturer != null) |
| | | 2445 | | |
| | | 2446 | | { |
| | 0 | 2447 | | order.Manufacturer = manufacturer; |
| | | 2448 | | } |
| | | 2449 | | } |
| | | 2450 | | } |
| | | 2451 | | |
| | | 2452 | | else |
| | | 2453 | | |
| | | 2454 | | { |
| | 0 | 2455 | | order.Manufacturer = _context.Manufacturers.FirstOrDefault(m => m.Id == selectedManufacturer.Id); |
| | | 2456 | | } |
| | | 2457 | | } |
| | | 2458 | | |
| | | 2459 | | |
| | 0 | 2460 | | if (dataColumn.TryGetValue("Код валюты отправления", out var currencyName)) |
| | | 2461 | | |
| | | 2462 | | { |
| | 0 | 2463 | | Currency currency = _context.Currencys.FirstOrDefault(c => c.Name == currencyName); |
| | | 2464 | | |
| | | 2465 | | |
| | 0 | 2466 | | if (currency != null) |
| | | 2467 | | |
| | | 2468 | | { |
| | 0 | 2469 | | order.Сurrency = currency; |
| | | 2470 | | } |
| | | 2471 | | |
| | | 2472 | | else |
| | | 2473 | | |
| | | 2474 | | { |
| | 0 | 2475 | | var newCurrency = new Currency |
| | 0 | 2476 | | |
| | 0 | 2477 | | { |
| | 0 | 2478 | | Name = currencyName |
| | 0 | 2479 | | }; |
| | | 2480 | | |
| | | 2481 | | |
| | 0 | 2482 | | _context.Currencys.Add(newCurrency); |
| | | 2483 | | |
| | 0 | 2484 | | await _context.SaveChangesAsync(); |
| | | 2485 | | |
| | 0 | 2486 | | order.Сurrency = newCurrency; |
| | 0 | 2487 | | } |
| | | 2488 | | } |
| | | 2489 | | |
| | | 2490 | | |
| | 0 | 2491 | | order.Supplier = null; |
| | | 2492 | | |
| | 0 | 2493 | | order.PurchasePrice = null; |
| | | 2494 | | |
| | | 2495 | | |
| | 0 | 2496 | | if (order.ProductInfo == null && dataColumn.TryGetValue("Артикул", out var productArticle)) |
| | | 2497 | | |
| | | 2498 | | { |
| | 0 | 2499 | | Product product = _context.Products.FirstOrDefault(p => p.Article == productArticle); |
| | | 2500 | | |
| | | 2501 | | |
| | 0 | 2502 | | if (product != null) |
| | | 2503 | | |
| | | 2504 | | { |
| | 0 | 2505 | | order.ProductInfo = product; |
| | | 2506 | | } |
| | | 2507 | | |
| | | 2508 | | else |
| | | 2509 | | |
| | | 2510 | | { |
| | 0 | 2511 | | product = new Product |
| | 0 | 2512 | | |
| | 0 | 2513 | | { |
| | 0 | 2514 | | Article = productArticle |
| | 0 | 2515 | | }; |
| | | 2516 | | |
| | | 2517 | | |
| | 0 | 2518 | | _context.Products.Add(product); |
| | | 2519 | | |
| | 0 | 2520 | | await _context.SaveChangesAsync(); |
| | | 2521 | | |
| | 0 | 2522 | | order.ProductInfo = product; |
| | | 2523 | | } |
| | 0 | 2524 | | } |
| | | 2525 | | |
| | 0 | 2526 | | else if (order.ProductInfo == null && !dataColumn.TryGetValue("Артикул", out var nullProductArticle)) |
| | | 2527 | | |
| | | 2528 | | { |
| | 0 | 2529 | | var product = new Product(); |
| | | 2530 | | |
| | | 2531 | | |
| | 0 | 2532 | | _context.Products.Add(product); |
| | | 2533 | | |
| | 0 | 2534 | | _context.SaveChanges(); |
| | | 2535 | | |
| | | 2536 | | |
| | 0 | 2537 | | order.ProductInfo = product; |
| | | 2538 | | } |
| | | 2539 | | |
| | | 2540 | | |
| | 0 | 2541 | | order.DeliveryCity = dataColumn.TryGetValue("Город доставки", out var deliveryCity) |
| | 0 | 2542 | | ? deliveryCity?.ToString() |
| | 0 | 2543 | | : null; |
| | | 2544 | | |
| | | 2545 | | |
| | | 2546 | | // Проверяем "Статус клиента" сначала, затем "Статус клинта" (для обратной совместимости), затем "Статус" |
| | | 2547 | | |
| | 0 | 2548 | | string clientStatusValue1 = null; |
| | | 2549 | | |
| | 0 | 2550 | | if (dataColumn.TryGetValue("Статус клиента", out clientStatusValue1)) |
| | | 2551 | | |
| | | 2552 | | { |
| | 0 | 2553 | | order.ClientStatus = await GetOrCreateClientStatusAsync(clientStatusValue1?.ToString()); |
| | | 2554 | | } |
| | | 2555 | | |
| | 0 | 2556 | | else if (dataColumn.TryGetValue("Статус клинта", out var clientStauts)) |
| | | 2557 | | |
| | | 2558 | | { |
| | 0 | 2559 | | order.ClientStatus = await GetOrCreateClientStatusAsync(clientStauts?.ToString()); |
| | | 2560 | | } |
| | | 2561 | | |
| | 0 | 2562 | | else if (dataColumn.TryGetValue("Статус", out var status)) |
| | | 2563 | | |
| | | 2564 | | { |
| | 0 | 2565 | | order.ClientStatus = await GetOrCreateClientStatusAsync(status?.ToString()); |
| | | 2566 | | } |
| | | 2567 | | |
| | 0 | 2568 | | else if (selectedClientStatus != null) |
| | | 2569 | | |
| | | 2570 | | { |
| | 0 | 2571 | | order.ClientStatus = await GetOrCreateClientStatusAsync(selectedClientStatus); |
| | | 2572 | | } |
| | | 2573 | | |
| | | 2574 | | else |
| | | 2575 | | |
| | | 2576 | | { |
| | 0 | 2577 | | order.ClientStatus = null; |
| | | 2578 | | } |
| | | 2579 | | |
| | | 2580 | | |
| | 0 | 2581 | | if (order.AppStatus == null) |
| | | 2582 | | |
| | | 2583 | | { |
| | 0 | 2584 | | string statusName = "Не указан"; |
| | | 2585 | | |
| | | 2586 | | |
| | 0 | 2587 | | AppStatus appStatus = _context.AppStatuses.FirstOrDefault(c => c.Name == statusName); |
| | | 2588 | | |
| | | 2589 | | |
| | 0 | 2590 | | if (appStatus != null) |
| | | 2591 | | |
| | | 2592 | | { |
| | 0 | 2593 | | order.AppStatus = appStatus; |
| | | 2594 | | } |
| | | 2595 | | |
| | | 2596 | | else |
| | | 2597 | | |
| | | 2598 | | { |
| | 0 | 2599 | | var newStatus = new AppStatus { Name = statusName }; |
| | | 2600 | | |
| | | 2601 | | |
| | 0 | 2602 | | _context.AppStatuses.Add(newStatus); |
| | | 2603 | | |
| | 0 | 2604 | | await _context.SaveChangesAsync(); |
| | | 2605 | | |
| | 0 | 2606 | | order.AppStatus = newStatus; |
| | 0 | 2607 | | } |
| | | 2608 | | } |
| | | 2609 | | |
| | | 2610 | | |
| | 0 | 2611 | | if (order.Supplier == null && selectedSupplier.Id == 0) |
| | | 2612 | | |
| | | 2613 | | { |
| | 0 | 2614 | | string supplierName = "Не указан"; |
| | | 2615 | | |
| | | 2616 | | |
| | 0 | 2617 | | Supplier supplier = _context.Suppliers.FirstOrDefault(c => c.Name == supplierName); |
| | | 2618 | | |
| | | 2619 | | |
| | 0 | 2620 | | if (supplier != null) |
| | | 2621 | | |
| | | 2622 | | { |
| | 0 | 2623 | | order.Supplier = supplier; |
| | | 2624 | | } |
| | | 2625 | | |
| | | 2626 | | else |
| | | 2627 | | |
| | | 2628 | | { |
| | 0 | 2629 | | var newSupplier = new Supplier { Name = supplierName }; |
| | | 2630 | | |
| | | 2631 | | |
| | 0 | 2632 | | _context.Suppliers.Add(newSupplier); |
| | | 2633 | | |
| | 0 | 2634 | | await _context.SaveChangesAsync(); |
| | | 2635 | | |
| | 0 | 2636 | | order.Supplier = newSupplier; |
| | 0 | 2637 | | } |
| | | 2638 | | } |
| | | 2639 | | |
| | 0 | 2640 | | else if (selectedSupplier.Id != 0) |
| | | 2641 | | |
| | | 2642 | | { |
| | 0 | 2643 | | order.Supplier = _context.Suppliers.FirstOrDefault(m => m.Id == selectedSupplier.Id); |
| | | 2644 | | } |
| | | 2645 | | |
| | | 2646 | | |
| | 0 | 2647 | | var numberStyles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; |
| | | 2648 | | |
| | | 2649 | | |
| | 0 | 2650 | | if (order.Price == null && |
| | 0 | 2651 | | dataColumn.TryGetValue("Целая часть", out var integerPartStr) && |
| | 0 | 2652 | | dataColumn.TryGetValue("Дробная часть", out var fractionalPartStr)) |
| | | 2653 | | |
| | | 2654 | | { |
| | 0 | 2655 | | if (int.TryParse(integerPartStr, out var integerPart) && |
| | 0 | 2656 | | int.TryParse(fractionalPartStr, out var fractionalPart)) |
| | | 2657 | | |
| | | 2658 | | { |
| | 0 | 2659 | | order.Price = integerPart + (decimal)fractionalPart / 100; |
| | | 2660 | | } |
| | | 2661 | | } |
| | | 2662 | | |
| | | 2663 | | |
| | 0 | 2664 | | if (dataColumn.TryGetValue("Сумма отправления", out var shipmentAmountStr) && |
| | 0 | 2665 | | decimal.TryParse(DelSubStr(shipmentAmountStr), numberStyles, cultureDateInfo, out var shipmentAmount)) |
| | | 2666 | | |
| | | 2667 | | { |
| | 0 | 2668 | | order.ShipmentAmount = shipmentAmount; |
| | | 2669 | | } |
| | | 2670 | | |
| | 0 | 2671 | | else if (order.Price != null && order.Quantity != null) |
| | | 2672 | | |
| | | 2673 | | { |
| | 0 | 2674 | | order.ShipmentAmount = order.Price * order.Quantity; |
| | | 2675 | | } |
| | | 2676 | | |
| | | 2677 | | |
| | | 2678 | | // Часть поставщиков (Exist и другие) не присылает колонку «Цена сайта» — в таких файлах |
| | | 2679 | | // единственная цена лежит в «Цена», поэтому берём её, иначе цена сайта осталась бы нулевой. |
| | 0 | 2680 | | order.ProductInfo.CurrentPriceWithDiscount = |
| | 0 | 2681 | | dataColumn.TryGetValue("Цена сайта", out var priceWithDiscountStr) && |
| | 0 | 2682 | | decimal.TryParse(priceWithDiscountStr, numberStyles, cultureDateInfo, out var priceWithDiscount) && |
| | 0 | 2683 | | priceWithDiscount > 0 |
| | 0 | 2684 | | ? priceWithDiscount |
| | 0 | 2685 | | : order.Price ?? 0; |
| | | 2686 | | |
| | | 2687 | | |
| | 0 | 2688 | | order.MaxOzonCommission = dataColumn.TryGetValue("Максимальная комиссия", out var maxOzonCommissionStr) |
| | 0 | 2689 | | ? decimal.TryParse(maxOzonCommissionStr, numberStyles, cultureDateInfo, out var maxOzonCommission) |
| | 0 | 2690 | | ? maxOzonCommission |
| | 0 | 2691 | | : 0 |
| | 0 | 2692 | | : 0; |
| | | 2693 | | |
| | | 2694 | | |
| | 0 | 2695 | | order.MinOzonCommission = dataColumn.TryGetValue("Минимальная комиссия", out var minOzonCommissionStr) |
| | 0 | 2696 | | ? decimal.TryParse(minOzonCommissionStr, numberStyles, cultureDateInfo, out var minOzonCommission) |
| | 0 | 2697 | | ? minOzonCommission |
| | 0 | 2698 | | : 0 |
| | 0 | 2699 | | : 0; |
| | | 2700 | | |
| | | 2701 | | |
| | 0 | 2702 | | order.PurchasePrice = dataColumn.TryGetValue("Цена закупки", out var purchasePriceStr) |
| | 0 | 2703 | | ? decimal.TryParse(purchasePriceStr, numberStyles, cultureDateInfo, out var purchasePrice) |
| | 0 | 2704 | | ? purchasePrice |
| | 0 | 2705 | | : 0 |
| | 0 | 2706 | | : 0; |
| | | 2707 | | |
| | | 2708 | | |
| | 0 | 2709 | | if (!string.IsNullOrWhiteSpace(deliveryName)) |
| | | 2710 | | |
| | | 2711 | | { |
| | 0 | 2712 | | var delivery = await _deliveryService.GetOrCreateDeliveryAsync(deliveryName, deliveryName); |
| | | 2713 | | |
| | | 2714 | | |
| | 0 | 2715 | | order.Delivery = delivery; |
| | | 2716 | | |
| | 0 | 2717 | | order.DeliveryId = delivery.Id; |
| | | 2718 | | } |
| | | 2719 | | |
| | | 2720 | | |
| | 0 | 2721 | | if (order.ProductInfo != null && string.IsNullOrEmpty(order.ProductInfo.ImageUrl) |
| | 0 | 2722 | | && !string.IsNullOrEmpty(_imageBaseUrl)) |
| | | 2723 | | { |
| | 0 | 2724 | | string? manufacturerCode = order.Manufacturer?.Code; |
| | 0 | 2725 | | string? productArticleForImage = article?.ToString(); |
| | | 2726 | | |
| | 0 | 2727 | | if (!string.IsNullOrEmpty(manufacturerCode) && !string.IsNullOrEmpty(productArticleForImage)) |
| | | 2728 | | { |
| | 0 | 2729 | | var normalizedArticle = NormalizeArticle(productArticleForImage); |
| | 0 | 2730 | | var normalizedManufacturer = manufacturerCode.ToUpperInvariant(); |
| | | 2731 | | |
| | 0 | 2732 | | var imgUrl = $"{_imageBaseUrl}/{normalizedManufacturer}/{normalizedArticle}_1.jpg"; |
| | | 2733 | | |
| | 0 | 2734 | | if (await ImageExistsAsync(imgUrl)) |
| | | 2735 | | { |
| | 0 | 2736 | | order.ProductInfo.ImageUrl = imgUrl; |
| | | 2737 | | } |
| | 0 | 2738 | | } |
| | | 2739 | | } |
| | | 2740 | | |
| | | 2741 | | |
| | 0 | 2742 | | order = SetCorrectProductKey(order); |
| | | 2743 | | |
| | | 2744 | | |
| | 0 | 2745 | | order.FromFile = true; |
| | | 2746 | | |
| | 0 | 2747 | | order.UpdatedBy = "Excel"; |
| | | 2748 | | |
| | | 2749 | | |
| | 0 | 2750 | | _context.SaveChanges(); |
| | | 2751 | | |
| | | 2752 | | |
| | 0 | 2753 | | return order; |
| | 0 | 2754 | | } |
| | | 2755 | | |
| | | 2756 | | private static string NormalizeArticle(string input) |
| | | 2757 | | { |
| | 0 | 2758 | | if (string.IsNullOrEmpty(input)) |
| | 0 | 2759 | | return string.Empty; |
| | | 2760 | | |
| | | 2761 | | // Удаляем всё кроме букв и цифр |
| | 0 | 2762 | | var cleaned = Regex.Replace(input, "[^a-zA-Z0-9]", ""); |
| | | 2763 | | |
| | 0 | 2764 | | return cleaned.ToUpperInvariant(); |
| | | 2765 | | } |
| | | 2766 | | |
| | | 2767 | | private async Task<bool> ImageExistsAsync(string url) |
| | | 2768 | | { |
| | | 2769 | | try |
| | | 2770 | | { |
| | 0 | 2771 | | using var httpClient = _httpClientFactory.CreateClient(); |
| | 0 | 2772 | | using var request = new HttpRequestMessage(HttpMethod.Head, url); |
| | | 2773 | | |
| | 0 | 2774 | | var response = await httpClient.SendAsync(request); |
| | 0 | 2775 | | return response.IsSuccessStatusCode; |
| | | 2776 | | } |
| | 0 | 2777 | | catch |
| | | 2778 | | { |
| | 0 | 2779 | | return false; |
| | | 2780 | | } |
| | 0 | 2781 | | } |
| | | 2782 | | |
| | | 2783 | | private async Task<Order> CastToModelFromExcelForEmEx(Dictionary<string, string> dataColumn, |
| | | 2784 | | OzonClient client, |
| | | 2785 | | Warehouse warehouse, |
| | | 2786 | | DateTime selectedShippingDate, |
| | | 2787 | | DateTime selectedProcessingDate, |
| | | 2788 | | string deliveryName) |
| | | 2789 | | |
| | | 2790 | | { |
| | 0 | 2791 | | var cultureDateInfo = new CultureInfo("ru-RU"); |
| | | 2792 | | |
| | 0 | 2793 | | var numberStyles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; |
| | | 2794 | | |
| | 0 | 2795 | | Order order = new(); |
| | | 2796 | | |
| | | 2797 | | |
| | 0 | 2798 | | order.OzonClient = client; |
| | | 2799 | | |
| | 0 | 2800 | | order.ShipmentWarehouse = warehouse; |
| | | 2801 | | |
| | 0 | 2802 | | order.ShippingDate = selectedShippingDate; |
| | | 2803 | | |
| | 0 | 2804 | | order.ProcessingDate = selectedProcessingDate; |
| | | 2805 | | |
| | 0 | 2806 | | if (!string.IsNullOrWhiteSpace(deliveryName)) |
| | | 2807 | | |
| | | 2808 | | { |
| | 0 | 2809 | | var delivery = await _deliveryService.GetOrCreateDeliveryAsync(deliveryName, deliveryName); |
| | | 2810 | | |
| | | 2811 | | |
| | 0 | 2812 | | order.Delivery = delivery; |
| | | 2813 | | |
| | 0 | 2814 | | order.DeliveryId = delivery.Id; |
| | | 2815 | | } |
| | | 2816 | | |
| | | 2817 | | |
| | 0 | 2818 | | order.ShipmentNumber = dataColumn.TryGetValue("5", out var shipmentNumber) |
| | 0 | 2819 | | ? shipmentNumber |
| | 0 | 2820 | | : string.Empty; |
| | | 2821 | | |
| | | 2822 | | |
| | 0 | 2823 | | order.ProductName = dataColumn.TryGetValue("6", out var productName) |
| | 0 | 2824 | | ? productName |
| | 0 | 2825 | | : string.Empty; |
| | | 2826 | | |
| | | 2827 | | |
| | 0 | 2828 | | order.ProductKey = dataColumn.TryGetValue("4", out var article) |
| | 0 | 2829 | | ? article |
| | 0 | 2830 | | : string.Empty; |
| | | 2831 | | |
| | | 2832 | | |
| | 0 | 2833 | | var produserName = dataColumn.TryGetValue("2", out var prodName) |
| | 0 | 2834 | | ? prodName |
| | 0 | 2835 | | : string.Empty; |
| | | 2836 | | |
| | | 2837 | | |
| | 0 | 2838 | | await SetEtProducerByNameAndCode(order, produserName); |
| | | 2839 | | |
| | 0 | 2840 | | SetCorrectProductKey(order); |
| | | 2841 | | |
| | | 2842 | | |
| | 0 | 2843 | | order.Price = dataColumn.TryGetValue("12", out var priceStr) |
| | 0 | 2844 | | ? decimal.TryParse(priceStr.Replace('.', ','), numberStyles, cultureDateInfo, out var price) |
| | 0 | 2845 | | ? price |
| | 0 | 2846 | | : 0 |
| | 0 | 2847 | | : 0; |
| | | 2848 | | |
| | | 2849 | | |
| | 0 | 2850 | | order.ShipmentAmount = dataColumn.TryGetValue("13", out var shipmentAmountStr) |
| | 0 | 2851 | | ? decimal.TryParse(shipmentAmountStr.Replace('.', ','), numberStyles, cultureDateInfo, |
| | 0 | 2852 | | out var shipmentAmount) |
| | 0 | 2853 | | ? shipmentAmount |
| | 0 | 2854 | | : 0 |
| | 0 | 2855 | | : 0; |
| | | 2856 | | |
| | | 2857 | | |
| | 0 | 2858 | | order.Quantity = dataColumn.TryGetValue("8", out var quantityStr) && |
| | 0 | 2859 | | int.TryParse(DelSubStr(quantityStr), out var quantity) |
| | 0 | 2860 | | ? quantity |
| | 0 | 2861 | | : (int?)null; |
| | | 2862 | | |
| | | 2863 | | |
| | 0 | 2864 | | if (order.ProductInfo == null && dataColumn.TryGetValue("4", out var productArticle)) |
| | | 2865 | | |
| | | 2866 | | { |
| | 0 | 2867 | | Product product = _context.Products.FirstOrDefault(p => p.Article == productArticle); |
| | | 2868 | | |
| | | 2869 | | |
| | 0 | 2870 | | if (product != null) |
| | | 2871 | | |
| | | 2872 | | { |
| | 0 | 2873 | | order.ProductInfo = product; |
| | | 2874 | | } |
| | | 2875 | | |
| | | 2876 | | else |
| | | 2877 | | |
| | | 2878 | | { |
| | 0 | 2879 | | product = new Product |
| | 0 | 2880 | | |
| | 0 | 2881 | | { |
| | 0 | 2882 | | Article = productArticle |
| | 0 | 2883 | | }; |
| | | 2884 | | |
| | | 2885 | | |
| | 0 | 2886 | | _context.Products.Add(product); |
| | | 2887 | | |
| | 0 | 2888 | | await _context.SaveChangesAsync(); |
| | | 2889 | | |
| | 0 | 2890 | | order.ProductInfo = product; |
| | | 2891 | | } |
| | 0 | 2892 | | } |
| | | 2893 | | |
| | 0 | 2894 | | else if (order.ProductInfo == null && !dataColumn.TryGetValue("4", out var nullProductArticle)) |
| | | 2895 | | |
| | | 2896 | | { |
| | 0 | 2897 | | var product = new Product(); |
| | | 2898 | | |
| | | 2899 | | |
| | 0 | 2900 | | _context.Products.Add(product); |
| | | 2901 | | |
| | 0 | 2902 | | _context.SaveChanges(); |
| | | 2903 | | |
| | | 2904 | | |
| | 0 | 2905 | | order.ProductInfo = product; |
| | | 2906 | | } |
| | | 2907 | | |
| | | 2908 | | |
| | 0 | 2909 | | if (order.AppStatus == null) |
| | | 2910 | | |
| | | 2911 | | { |
| | 0 | 2912 | | string statusName = "Не указан"; |
| | | 2913 | | |
| | | 2914 | | |
| | 0 | 2915 | | AppStatus appStatus = _context.AppStatuses.FirstOrDefault(c => c.Name == statusName); |
| | | 2916 | | |
| | | 2917 | | |
| | 0 | 2918 | | if (appStatus != null) |
| | | 2919 | | |
| | | 2920 | | { |
| | 0 | 2921 | | order.AppStatus = appStatus; |
| | | 2922 | | } |
| | | 2923 | | |
| | | 2924 | | else |
| | | 2925 | | |
| | | 2926 | | { |
| | 0 | 2927 | | var newStatus = new AppStatus { Name = statusName }; |
| | | 2928 | | |
| | | 2929 | | |
| | 0 | 2930 | | _context.AppStatuses.Add(newStatus); |
| | | 2931 | | |
| | 0 | 2932 | | await _context.SaveChangesAsync(); |
| | | 2933 | | |
| | 0 | 2934 | | order.AppStatus = newStatus; |
| | 0 | 2935 | | } |
| | | 2936 | | } |
| | | 2937 | | |
| | | 2938 | | |
| | 0 | 2939 | | if (order.ProductInfo != null && string.IsNullOrEmpty(order.ProductInfo.ImageUrl) |
| | 0 | 2940 | | && !string.IsNullOrEmpty(_imageBaseUrl)) |
| | | 2941 | | { |
| | 0 | 2942 | | string? productArticleForImage = article?.ToString(); |
| | | 2943 | | |
| | 0 | 2944 | | if (!string.IsNullOrEmpty(produserName) && !string.IsNullOrEmpty(productArticleForImage)) |
| | | 2945 | | { |
| | 0 | 2946 | | var imgUrl = $"{_imageBaseUrl}/{produserName.ToUpper()}/{productArticleForImage}_1.jpg"; |
| | 0 | 2947 | | order.ProductInfo.ImageUrl = imgUrl; |
| | | 2948 | | |
| | | 2949 | | } |
| | | 2950 | | } |
| | | 2951 | | |
| | | 2952 | | |
| | 0 | 2953 | | order.Key = order.ShipmentNumber + order.ProductKey; |
| | | 2954 | | |
| | | 2955 | | |
| | 0 | 2956 | | order.FromFile = true; |
| | | 2957 | | |
| | 0 | 2958 | | order.UpdatedBy = "Excel"; |
| | | 2959 | | |
| | | 2960 | | |
| | 0 | 2961 | | return order; |
| | 0 | 2962 | | } |
| | | 2963 | | |
| | | 2964 | | |
| | | 2965 | | private Order SetCorrectProductKey(Order order) |
| | | 2966 | | |
| | | 2967 | | { |
| | 0 | 2968 | | string pattern = @"^[A-Za-z0-9\-[\]]+=[A-Za-z0-9\[\]]+$"; |
| | | 2969 | | |
| | | 2970 | | |
| | 0 | 2971 | | Regex regex = new Regex(pattern); |
| | | 2972 | | |
| | 0 | 2973 | | Match match = regex.Match(order.ProductKey); |
| | | 2974 | | |
| | | 2975 | | |
| | 0 | 2976 | | if (match.Success) |
| | | 2977 | | |
| | | 2978 | | { |
| | 0 | 2979 | | order.Article = Regex.Replace(order.ProductKey.Substring(0, order.ProductKey.IndexOf('=')), |
| | 0 | 2980 | | "[^A-Za-z0-9]", ""); |
| | | 2981 | | |
| | 0 | 2982 | | return order; |
| | | 2983 | | } |
| | | 2984 | | |
| | | 2985 | | |
| | 0 | 2986 | | string cleanedArticle = Regex.Replace(order.ProductKey, "[^A-Za-z0-9]", ""); |
| | | 2987 | | |
| | 0 | 2988 | | var key = "NON"; |
| | | 2989 | | |
| | 0 | 2990 | | if (order.EtProducer != null) |
| | | 2991 | | |
| | | 2992 | | { |
| | 0 | 2993 | | key = order.EtProducer != null && order.EtProducer.MarketPrefix != null |
| | 0 | 2994 | | ? $"={order.EtProducer.MarketPrefix}" |
| | 0 | 2995 | | : "="; |
| | | 2996 | | } |
| | | 2997 | | |
| | | 2998 | | |
| | 0 | 2999 | | if (order.EtProducerId.HasValue && order.EtProducerId != 0) |
| | | 3000 | | |
| | | 3001 | | { |
| | 0 | 3002 | | var etProducer = _etProducerDataServices.GetEtProducer(order.EtProducerId.Value); |
| | | 3003 | | |
| | 0 | 3004 | | key = etProducer != null && etProducer.MarketPrefix != null |
| | 0 | 3005 | | ? $"={etProducer.MarketPrefix}" |
| | 0 | 3006 | | : "="; |
| | | 3007 | | } |
| | | 3008 | | |
| | | 3009 | | |
| | 0 | 3010 | | order.Article = cleanedArticle; |
| | | 3011 | | |
| | 0 | 3012 | | order.ProductKey = cleanedArticle + key; |
| | | 3013 | | |
| | | 3014 | | |
| | 0 | 3015 | | return order; |
| | | 3016 | | } |
| | | 3017 | | |
| | | 3018 | | |
| | | 3019 | | private string SetCorrectStatus(string status) |
| | | 3020 | | |
| | | 3021 | | { |
| | 0 | 3022 | | if (status == null) |
| | | 3023 | | |
| | | 3024 | | { |
| | 0 | 3025 | | return null; |
| | | 3026 | | } |
| | | 3027 | | |
| | | 3028 | | |
| | 0 | 3029 | | if (status == "Отменен") |
| | | 3030 | | |
| | | 3031 | | { |
| | 0 | 3032 | | status = "Отменён"; |
| | | 3033 | | } |
| | | 3034 | | |
| | | 3035 | | |
| | 0 | 3036 | | return status; |
| | | 3037 | | } |
| | | 3038 | | |
| | | 3039 | | |
| | | 3040 | | private async Task<ClientStatus?> GetOrCreateClientStatusAsync(string? statusName) |
| | | 3041 | | |
| | | 3042 | | { |
| | 0 | 3043 | | if (string.IsNullOrEmpty(statusName)) |
| | | 3044 | | |
| | | 3045 | | { |
| | 0 | 3046 | | return null; |
| | | 3047 | | } |
| | | 3048 | | |
| | | 3049 | | |
| | 0 | 3050 | | string correctedStatus = SetCorrectStatus(statusName); |
| | | 3051 | | |
| | 0 | 3052 | | if (string.IsNullOrEmpty(correctedStatus)) |
| | | 3053 | | |
| | | 3054 | | { |
| | 0 | 3055 | | return null; |
| | | 3056 | | } |
| | | 3057 | | |
| | | 3058 | | |
| | 0 | 3059 | | var clientStatus = await _context.ClientStatuses |
| | 0 | 3060 | | .FirstOrDefaultAsync(cs => cs.Name == correctedStatus); |
| | | 3061 | | |
| | | 3062 | | |
| | 0 | 3063 | | if (clientStatus == null) |
| | | 3064 | | |
| | | 3065 | | { |
| | 0 | 3066 | | clientStatus = new ClientStatus { Name = correctedStatus }; |
| | | 3067 | | |
| | 0 | 3068 | | await _context.ClientStatuses.AddAsync(clientStatus); |
| | | 3069 | | |
| | 0 | 3070 | | await _context.SaveChangesAsync(); |
| | | 3071 | | } |
| | | 3072 | | |
| | | 3073 | | |
| | 0 | 3074 | | return clientStatus; |
| | 0 | 3075 | | } |
| | | 3076 | | |
| | | 3077 | | |
| | | 3078 | | private (decimal, decimal, string, string, decimal, decimal) CalculateСommissions(JToken jsonOrder, Order order) |
| | | 3079 | | |
| | | 3080 | | { |
| | 0 | 3081 | | JToken productPrices = jsonOrder["productPricesWithArticle"]; |
| | | 3082 | | |
| | 0 | 3083 | | JToken productСommissions = productPrices["commissions"]; |
| | | 3084 | | |
| | | 3085 | | |
| | | 3086 | | // Используем Value<decimal>() вместо .ToString() + ConvertNumberByRegion. |
| | | 3087 | | // JToken.Value<decimal>() читает числовое значение напрямую из JSON без |
| | | 3088 | | // преобразования в строку, поэтому не зависит от локали сервера (ru-RU, de-DE и т.д.) |
| | | 3089 | | // и корректно работает на любом окружении. |
| | 0 | 3090 | | decimal priceWithDiscount = productPrices["price"]?["marketing_seller_price"]?.Value<decimal>() ?? 0; |
| | | 3091 | | |
| | 0 | 3092 | | decimal price = productPrices["price"]?["price"]?.Value<decimal>() ?? 0; |
| | | 3093 | | |
| | 0 | 3094 | | decimal percentFbs = productСommissions?["sales_percent_fbs"]?.Value<decimal>() ?? 0; |
| | | 3095 | | |
| | 0 | 3096 | | decimal acquiring = productPrices["acquiring"]?.Value<decimal>() ?? 0; |
| | | 3097 | | |
| | 0 | 3098 | | decimal delivToCustomer = productСommissions?["fbs_deliv_to_customer_amount"]?.Value<decimal>() ?? 0; |
| | | 3099 | | |
| | 0 | 3100 | | decimal fbsFirstMileMax = productСommissions?["fbs_first_mile_max_amount"]?.Value<decimal>() ?? 0; |
| | | 3101 | | |
| | 0 | 3102 | | decimal fbsDirectFlowTransMax = productСommissions?["fbs_direct_flow_trans_max_amount"]?.Value<decimal>() ?? |
| | | 3103 | | |
| | 0 | 3104 | | decimal fbsFirstMileMin = productСommissions?["fbs_first_mile_min_amount"]?.Value<decimal>() ?? 0; |
| | | 3105 | | |
| | 0 | 3106 | | decimal fbsDirectFlowTransMin = productСommissions?["fbs_direct_flow_trans_min_amount"]?.Value<decimal>() ?? |
| | | 3107 | | |
| | | 3108 | | |
| | | 3109 | | // Комиссия рассчитывается от цены продажи (marketing_seller_price), |
| | | 3110 | | // а не от базовой цены (price) — именно так считает Ozon. |
| | 0 | 3111 | | decimal salesСommission = priceWithDiscount / 100 * percentFbs; |
| | | 3112 | | |
| | 0 | 3113 | | decimal standaertSum = acquiring + delivToCustomer + salesСommission; |
| | | 3114 | | |
| | | 3115 | | |
| | 0 | 3116 | | decimal maxСommission = standaertSum + fbsFirstMileMax + fbsDirectFlowTransMax; |
| | | 3117 | | |
| | 0 | 3118 | | decimal minCommission = standaertSum + fbsFirstMileMin + fbsDirectFlowTransMin; |
| | | 3119 | | |
| | | 3120 | | |
| | 0 | 3121 | | string sb1 = BuildCommissionInfo( |
| | 0 | 3122 | | salesСommission, |
| | 0 | 3123 | | acquiring, |
| | 0 | 3124 | | delivToCustomer, |
| | 0 | 3125 | | fbsFirstMileMax, |
| | 0 | 3126 | | fbsDirectFlowTransMax, |
| | 0 | 3127 | | maxСommission); |
| | | 3128 | | |
| | 0 | 3129 | | string sb2 = BuildCommissionInfo( |
| | 0 | 3130 | | salesСommission, |
| | 0 | 3131 | | acquiring, |
| | 0 | 3132 | | delivToCustomer, |
| | 0 | 3133 | | fbsFirstMileMin, |
| | 0 | 3134 | | fbsDirectFlowTransMin, |
| | 0 | 3135 | | minCommission); |
| | | 3136 | | |
| | | 3137 | | |
| | 0 | 3138 | | var (maxComment, minComment, min, max) = (sb1, sb2, minCommission, maxСommission); |
| | | 3139 | | |
| | | 3140 | | |
| | 0 | 3141 | | return (price, priceWithDiscount, maxComment, minComment, min, max); |
| | | 3142 | | } |
| | | 3143 | | |
| | | 3144 | | private static string BuildCommissionInfo( |
| | | 3145 | | decimal salesCommission, |
| | | 3146 | | decimal acquiring, |
| | | 3147 | | decimal lastMile, |
| | | 3148 | | decimal firstMile, |
| | | 3149 | | decimal directFlow, |
| | | 3150 | | decimal total) => |
| | 0 | 3151 | | $"Комиссия за продажу: {salesCommission.ToString("0.##", CultureInfo.InvariantCulture)} ₽; " + |
| | 0 | 3152 | | $"Эквайринг: {acquiring.ToString("0.##", CultureInfo.InvariantCulture)} ₽; " + |
| | 0 | 3153 | | $"Последняя миля FBS: {lastMile.ToString("0.##", CultureInfo.InvariantCulture)} ₽; " + |
| | 0 | 3154 | | $"Обработка отправления FBS: {firstMile.ToString("0.##", CultureInfo.InvariantCulture)} ₽; " + |
| | 0 | 3155 | | $"Магистраль FBS: {directFlow.ToString("0.##", CultureInfo.InvariantCulture)} ₽; " + |
| | 0 | 3156 | | $"Итого: {total.ToString("0.##", CultureInfo.InvariantCulture)} ₽"; |
| | | 3157 | | |
| | | 3158 | | |
| | | 3159 | | public decimal ConvertNumberByRegion(string number, string regionCode) |
| | | 3160 | | { |
| | | 3161 | | // API Ozon всегда возвращает числа с точкой (InvariantCulture). |
| | | 3162 | | // Файлы CSV-отчётов в ru-регионе используют запятую (ru-RU). |
| | | 3163 | | // |
| | | 3164 | | // ВАЖНО: нельзя использовать NumberStyles.Number с InvariantCulture — |
| | | 3165 | | // он включает AllowThousands, где запятая является разделителем тысяч. |
| | | 3166 | | // Это приводит к тому, что "25,88" (ru-RU десятичный) парсится как 2588. |
| | | 3167 | | // NumberStyles.Float использует только точку как десятичный разделитель |
| | | 3168 | | // и не содержит AllowThousands. |
| | 0 | 3169 | | if (decimal.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out var invariantResult)) |
| | 0 | 3170 | | return invariantResult; |
| | 0 | 3171 | | if (decimal.TryParse(number, NumberStyles.Number, new CultureInfo("ru-RU"), out var ruResult)) |
| | 0 | 3172 | | return ruResult; |
| | 0 | 3173 | | return 0; |
| | | 3174 | | } |
| | | 3175 | | |
| | | 3176 | | |
| | | 3177 | | private string DelSubStr(string str) |
| | | 3178 | | |
| | | 3179 | | { |
| | 0 | 3180 | | if (string.IsNullOrEmpty(str)) |
| | | 3181 | | |
| | | 3182 | | { |
| | 0 | 3183 | | return str; |
| | | 3184 | | } |
| | | 3185 | | |
| | | 3186 | | |
| | 0 | 3187 | | if (str.StartsWith("'")) |
| | | 3188 | | |
| | | 3189 | | { |
| | 0 | 3190 | | return str.Substring(1); |
| | | 3191 | | } |
| | | 3192 | | |
| | | 3193 | | |
| | 0 | 3194 | | return str; |
| | | 3195 | | } |
| | | 3196 | | |
| | | 3197 | | |
| | | 3198 | | private async Task<Order> SetEtProducerByCode(Order order, string extractedCode) |
| | | 3199 | | |
| | | 3200 | | { |
| | 0 | 3201 | | var producer = await _etProducerDataServices.GetRealIdAsyncByCode(extractedCode, order.ProductName); |
| | | 3202 | | |
| | 0 | 3203 | | if (producer != null) |
| | | 3204 | | |
| | | 3205 | | { |
| | 0 | 3206 | | order.EtProducerId = producer.RealId; |
| | | 3207 | | } |
| | | 3208 | | |
| | | 3209 | | |
| | 0 | 3210 | | return order; |
| | 0 | 3211 | | } |
| | | 3212 | | |
| | | 3213 | | |
| | | 3214 | | private async Task<Order> SetEtProducerByName(Order order, string name) |
| | | 3215 | | |
| | | 3216 | | { |
| | 0 | 3217 | | var producer = await _etProducerDataServices.GetRealIdAsyncByName(name); |
| | | 3218 | | |
| | 0 | 3219 | | if (producer != null) |
| | | 3220 | | |
| | | 3221 | | { |
| | 0 | 3222 | | order.EtProducerId = producer.RealId; |
| | | 3223 | | } |
| | | 3224 | | |
| | | 3225 | | |
| | 0 | 3226 | | return order; |
| | 0 | 3227 | | } |
| | | 3228 | | |
| | | 3229 | | |
| | | 3230 | | private async Task<Order> SetEtProducerByNameAndCode(Order order, string name) |
| | | 3231 | | |
| | | 3232 | | { |
| | 0 | 3233 | | var producer = await _etProducerDataServices.GetRealIdAsyncByName(name); |
| | | 3234 | | |
| | 0 | 3235 | | if (producer == null) |
| | | 3236 | | |
| | | 3237 | | { |
| | 0 | 3238 | | producer = await _etProducerDataServices.GetRealIdAsyncByCode(name); |
| | | 3239 | | } |
| | | 3240 | | |
| | | 3241 | | |
| | 0 | 3242 | | if (producer != null) |
| | | 3243 | | |
| | | 3244 | | { |
| | 0 | 3245 | | order.EtProducerId = producer.RealId; |
| | | 3246 | | } |
| | | 3247 | | |
| | | 3248 | | |
| | 0 | 3249 | | return order; |
| | 0 | 3250 | | } |
| | | 3251 | | |
| | | 3252 | | |
| | | 3253 | | private async Task CreateOrderPriceAndIndexes(Order order, JToken jsonOrder) |
| | | 3254 | | |
| | | 3255 | | { |
| | 0 | 3256 | | await Task.CompletedTask; |
| | | 3257 | | try |
| | | 3258 | | |
| | | 3259 | | { |
| | | 3260 | | // Проверяем наличие данных о ценах в JSON |
| | | 3261 | | |
| | 0 | 3262 | | var priceData = jsonOrder["productPricesWithArticle"]?["price"]; |
| | | 3263 | | |
| | 0 | 3264 | | var priceIndexesData = jsonOrder["productPricesWithArticle"]?["price_indexes"]; |
| | | 3265 | | |
| | | 3266 | | |
| | 0 | 3267 | | if (priceData == null || priceIndexesData == null) |
| | | 3268 | | |
| | 0 | 3269 | | return; |
| | | 3270 | | |
| | | 3271 | | |
| | | 3272 | | // Создаем OrderPrice |
| | | 3273 | | |
| | 0 | 3274 | | var orderPrice = new OrderPrice |
| | 0 | 3275 | | |
| | 0 | 3276 | | { |
| | 0 | 3277 | | OrderId = order.Id, |
| | 0 | 3278 | | |
| | 0 | 3279 | | AutoActionEnabled = priceData["auto_action_enabled"]?.Value<bool>() ?? false, |
| | 0 | 3280 | | |
| | 0 | 3281 | | CurrencyCode = priceData["currency_code"]?.ToString() ?? "RUB", |
| | 0 | 3282 | | |
| | 0 | 3283 | | MarketingPrice = priceData["marketing_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3284 | | |
| | 0 | 3285 | | MarketingSellerPrice = priceData["marketing_seller_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3286 | | |
| | 0 | 3287 | | MinPrice = priceData["min_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3288 | | |
| | 0 | 3289 | | OldPrice = priceData["old_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3290 | | |
| | 0 | 3291 | | Price = priceData["price"]?.Value<decimal>() ?? 0, |
| | 0 | 3292 | | |
| | 0 | 3293 | | RetailPrice = priceData["retail_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3294 | | |
| | 0 | 3295 | | Vat = priceData["vat"]?.Value<decimal>() ?? 0, |
| | 0 | 3296 | | |
| | 0 | 3297 | | AutoAddToOzonActionsListEnabled = |
| | 0 | 3298 | | priceData["auto_add_to_ozon_actions_list_enabled"]?.Value<bool>() ?? false, |
| | 0 | 3299 | | |
| | 0 | 3300 | | NetPrice = priceData["net_price"]?.Value<decimal>() ?? 0 |
| | 0 | 3301 | | }; |
| | | 3302 | | |
| | | 3303 | | |
| | | 3304 | | // Создаем PriceIndexes |
| | | 3305 | | |
| | 0 | 3306 | | var priceIndexes = new PriceIndexes |
| | 0 | 3307 | | |
| | 0 | 3308 | | { |
| | 0 | 3309 | | OrderPriceId = orderPrice.Id, |
| | 0 | 3310 | | |
| | 0 | 3311 | | // External index data |
| | 0 | 3312 | | |
| | 0 | 3313 | | ExternalMinPrice = priceIndexesData["external_index_data"]?["min_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3314 | | |
| | 0 | 3315 | | ExternalMinPriceCurrency = |
| | 0 | 3316 | | priceIndexesData["external_index_data"]?["min_price_currency"]?.ToString() ?? "RUB", |
| | 0 | 3317 | | |
| | 0 | 3318 | | ExternalPriceIndexValue = |
| | 0 | 3319 | | priceIndexesData["external_index_data"]?["price_index_value"]?.Value<decimal>() ?? 0, |
| | 0 | 3320 | | |
| | 0 | 3321 | | // Ozon index data |
| | 0 | 3322 | | |
| | 0 | 3323 | | OzonMinPrice = priceIndexesData["ozon_index_data"]?["min_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3324 | | |
| | 0 | 3325 | | OzonMinPriceCurrency = |
| | 0 | 3326 | | priceIndexesData["ozon_index_data"]?["min_price_currency"]?.ToString() ?? "RUB", |
| | 0 | 3327 | | |
| | 0 | 3328 | | OzonPriceIndexValue = |
| | 0 | 3329 | | priceIndexesData["ozon_index_data"]?["price_index_value"]?.Value<decimal>() ?? 0, |
| | 0 | 3330 | | |
| | 0 | 3331 | | // Self marketplaces index data |
| | 0 | 3332 | | |
| | 0 | 3333 | | SelfMarketplacesMinPrice = |
| | 0 | 3334 | | priceIndexesData["self_marketplaces_index_data"]?["min_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3335 | | |
| | 0 | 3336 | | SelfMarketplacesMinPriceCurrency = |
| | 0 | 3337 | | priceIndexesData["self_marketplaces_index_data"]?["min_price_currency"]?.ToString() ?? "RUB", |
| | 0 | 3338 | | |
| | 0 | 3339 | | SelfMarketplacesPriceIndexValue = |
| | 0 | 3340 | | priceIndexesData["self_marketplaces_index_data"]?["price_index_value"]?.Value<decimal>() ?? 0, |
| | 0 | 3341 | | |
| | 0 | 3342 | | ColorIndex = priceIndexesData["color_index"]?.ToString() ?? "WHITE" |
| | 0 | 3343 | | }; |
| | | 3344 | | |
| | | 3345 | | |
| | 0 | 3346 | | orderPrice.PriceIndexes = priceIndexes; |
| | | 3347 | | |
| | 0 | 3348 | | order.OrderPrice = orderPrice; |
| | 0 | 3349 | | } |
| | | 3350 | | |
| | 0 | 3351 | | catch (Exception ex) |
| | | 3352 | | |
| | | 3353 | | { |
| | | 3354 | | // Логируем ошибку, но не прерываем выполнение |
| | | 3355 | | |
| | 0 | 3356 | | Console.WriteLine($"Ошибка при создании OrderPrice и PriceIndexes: {ex.Message}"); |
| | 0 | 3357 | | } |
| | 0 | 3358 | | } |
| | | 3359 | | |
| | | 3360 | | /// <summary> |
| | | 3361 | | /// Преобразует уже полученный пакетный ответ <c>/v5/product/info/prices</c> в снимок. |
| | | 3362 | | /// Здесь находится только транспортное преобразование JSON → доменная модель; |
| | | 3363 | | /// дальнейшая работа с акциями выполняется по типизированным сущностям. |
| | | 3364 | | /// </summary> |
| | | 3365 | | private static OrderOzonPromotionSnapshot? CreateOzonPromotionSnapshot(JToken jsonOrder) |
| | | 3366 | | { |
| | 0 | 3367 | | var payload = jsonOrder["productPricesWithArticle"] as JObject; |
| | 0 | 3368 | | if (payload == null) |
| | 0 | 3369 | | return null; |
| | | 3370 | | |
| | 0 | 3371 | | var price = payload["price"]; |
| | 0 | 3372 | | var commissions = payload["commissions"]; |
| | 0 | 3373 | | var marketingActions = payload["marketing_actions"]; |
| | 0 | 3374 | | var priceIndexes = payload["price_indexes"]; |
| | 0 | 3375 | | var ozonActionsExist = marketingActions?["ozon_actions_exist"]?.Value<bool>() ?? false; |
| | | 3376 | | |
| | 0 | 3377 | | var snapshot = new OrderOzonPromotionSnapshot |
| | 0 | 3378 | | { |
| | 0 | 3379 | | OzonProductId = payload["product_id"]?.Value<long>() ?? 0, |
| | 0 | 3380 | | OfferId = payload["offer_id"]?.ToString() ?? jsonOrder["Артикул"]?.ToString() ?? string.Empty, |
| | 0 | 3381 | | CapturedAt = DateTime.UtcNow, |
| | 0 | 3382 | | OzonActionsExist = ozonActionsExist, |
| | 0 | 3383 | | AutoActionEnabled = price?["auto_action_enabled"]?.Value<bool>() ?? false, |
| | 0 | 3384 | | AutoAddToOzonActionsListEnabled = price?["auto_add_to_ozon_actions_list_enabled"]?.Value<bool>() ?? fals |
| | 0 | 3385 | | CurrencyCode = price?["currency_code"]?.ToString() ?? "RUB", |
| | 0 | 3386 | | MarketingPrice = price?["marketing_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3387 | | MarketingSellerPrice = price?["marketing_seller_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3388 | | MinPrice = price?["min_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3389 | | OldPrice = price?["old_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3390 | | Price = price?["price"]?.Value<decimal>() ?? 0, |
| | 0 | 3391 | | RetailPrice = price?["retail_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3392 | | NetPrice = price?["net_price"]?.Value<decimal>() ?? 0, |
| | 0 | 3393 | | Vat = price?["vat"]?.Value<decimal>() ?? 0, |
| | 0 | 3394 | | Acquiring = payload["acquiring"]?.Value<decimal>() ?? 0, |
| | 0 | 3395 | | VolumeWeight = payload["volume_weight"]?.Value<decimal>() ?? 0, |
| | 0 | 3396 | | FboCommissionPercent = commissions?["sales_percent_fbo"]?.Value<decimal>() ?? 0, |
| | 0 | 3397 | | FbsCommissionPercent = commissions?["sales_percent_fbs"]?.Value<decimal>() ?? 0, |
| | 0 | 3398 | | FbsDeliveryToCustomerAmount = commissions?["fbs_deliv_to_customer_amount"]?.Value<decimal>() ?? 0, |
| | 0 | 3399 | | FbsFirstMileMinAmount = commissions?["fbs_first_mile_min_amount"]?.Value<decimal>() ?? 0, |
| | 0 | 3400 | | FbsFirstMileMaxAmount = commissions?["fbs_first_mile_max_amount"]?.Value<decimal>() ?? 0, |
| | 0 | 3401 | | FbsDirectFlowMinAmount = commissions?["fbs_direct_flow_trans_min_amount"]?.Value<decimal>() ?? 0, |
| | 0 | 3402 | | FbsDirectFlowMaxAmount = commissions?["fbs_direct_flow_trans_max_amount"]?.Value<decimal>() ?? 0, |
| | 0 | 3403 | | ExternalPriceIndex = priceIndexes?["external_index_data"]?["price_index_value"]?.Value<decimal>() ?? 0, |
| | 0 | 3404 | | OzonPriceIndex = priceIndexes?["ozon_index_data"]?["price_index_value"]?.Value<decimal>() ?? 0, |
| | 0 | 3405 | | SelfMarketplacePriceIndex = priceIndexes?["self_marketplaces_index_data"]?["price_index_value"]?.Value<d |
| | 0 | 3406 | | CurrentPeriodFrom = marketingActions?["current_period_from"]?.Value<DateTime?>(), |
| | 0 | 3407 | | CurrentPeriodTo = marketingActions?["current_period_to"]?.Value<DateTime?>(), |
| | 0 | 3408 | | RawPricePayload = payload.ToString(Newtonsoft.Json.Formatting.None) |
| | 0 | 3409 | | }; |
| | | 3410 | | |
| | 0 | 3411 | | foreach (var action in marketingActions?["actions"]?.OfType<JObject>() ?? []) |
| | | 3412 | | { |
| | 0 | 3413 | | var title = action["title"]?.ToString() ?? string.Empty; |
| | 0 | 3414 | | snapshot.Conditions.Add(new OrderOzonPromotionCondition |
| | 0 | 3415 | | { |
| | 0 | 3416 | | SourceType = title.StartsWith("РК.", StringComparison.OrdinalIgnoreCase) |
| | 0 | 3417 | | ? OzonPromotionSourceType.SellerAction |
| | 0 | 3418 | | : OzonPromotionSourceType.Ozon, |
| | 0 | 3419 | | Title = title, |
| | 0 | 3420 | | Value = action["value"]?.Value<decimal?>(), |
| | 0 | 3421 | | DateFrom = action["date_from"]?.Value<DateTime?>(), |
| | 0 | 3422 | | DateTo = action["date_to"]?.Value<DateTime?>() |
| | 0 | 3423 | | }); |
| | | 3424 | | } |
| | | 3425 | | |
| | 0 | 3426 | | if (ozonActionsExist && snapshot.Conditions.All(x => x.SourceType != OzonPromotionSourceType.Ozon)) |
| | | 3427 | | { |
| | 0 | 3428 | | snapshot.Conditions.Add(new OrderOzonPromotionCondition |
| | 0 | 3429 | | { |
| | 0 | 3430 | | SourceType = OzonPromotionSourceType.Ozon, |
| | 0 | 3431 | | Title = "Акция Ozon", |
| | 0 | 3432 | | ActionPrice = snapshot.MarketingSellerPrice |
| | 0 | 3433 | | }); |
| | | 3434 | | } |
| | | 3435 | | |
| | 0 | 3436 | | snapshot.HasAnyPromotion = snapshot.OzonActionsExist || snapshot.Conditions.Count > 0; |
| | 0 | 3437 | | return snapshot; |
| | | 3438 | | } |
| | | 3439 | | } |
| | | 3440 | | } |