| | | 1 | | using System.Net; |
| | | 2 | | using System.Text; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.EntityFrameworkCore; |
| | | 5 | | using OzonDomains; |
| | | 6 | | using OzonDomains.Models; |
| | | 7 | | using OzonOrdersWeb.Areas.Studio2.Controllers.Base; |
| | | 8 | | using OzonOrdersWeb.ViewModels.OrderViewModels; |
| | | 9 | | using OzonRepositories.Context; |
| | | 10 | | using Services.ApiServices.OzonApi; |
| | | 11 | | using Services.ApiServices.OzonApi.Filters; |
| | | 12 | | using Services.CacheServices.Cache.OzonOrdersCache; |
| | | 13 | | using Services.CacheServices.Cache.UserCacheService; |
| | | 14 | | using Services.DataServices; |
| | | 15 | | using OzonOrdersWeb.WebServices.Currency; |
| | | 16 | | using Services.TransactionUtilsServices; |
| | | 17 | | using Services.CacheServices.Cache; |
| | | 18 | | using SlqStudio.Application.Services.EmailService; |
| | | 19 | | using Services.OzonWebhookServices; |
| | | 20 | | |
| | | 21 | | namespace OzonOrdersWeb.Areas.Studio2.Controllers.Transactions; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Контроллер транзакции "Отменен" |
| | | 25 | | /// </summary> |
| | | 26 | | public class CancelledTransactionController : BaseTransactionController |
| | | 27 | | { |
| | | 28 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 29 | | private readonly IEmailService? _emailService; |
| | | 30 | | private readonly OzonClientServices _ozonClientServices; |
| | 0 | 31 | | private readonly List<OzonCancelSuccessEntry> _ozonCancelSuccessEntries = new(); |
| | | 32 | | private readonly IOzonPostingCancellationService _cancellationService; |
| | | 33 | | |
| | | 34 | | public CancelledTransactionController( |
| | | 35 | | ApplicationDbContext context, |
| | | 36 | | AppStatusDataServices appStatusServices, |
| | | 37 | | OrdersDataServices orderServices, |
| | | 38 | | TransactionManager transactionManager, |
| | | 39 | | TransactionCache transactionCache, |
| | | 40 | | SupplierDataServices supplierDataServices, |
| | | 41 | | IUserCacheService userCacheService, |
| | | 42 | | ICurrencyRatesViewBagService currencyRatesViewBagService, |
| | | 43 | | CacheUpdater<Order> cacheUpdater, |
| | | 44 | | OrderCache orderCache, |
| | | 45 | | WarehouseDataServices warehouseDataServices, |
| | | 46 | | ExpenseTypeDataServices expenseTypeDataServices, |
| | | 47 | | OrderExtraExpenseDataServices orderExtraExpenseDataServices, |
| | | 48 | | StatusTransitionDataServices statusTransitionDataServices, |
| | | 49 | | IHttpClientFactory httpClientFactory, |
| | | 50 | | IEmailService? emailService, |
| | | 51 | | OzonClientServices ozonClientServices, |
| | | 52 | | IOzonPostingCancellationService cancellationService) |
| | 0 | 53 | | : base(context, appStatusServices, orderServices, transactionManager, transactionCache, |
| | 0 | 54 | | supplierDataServices, userCacheService, currencyRatesViewBagService, cacheUpdater, orderCache, |
| | 0 | 55 | | warehouseDataServices: warehouseDataServices, expenseTypeDataServices: expenseTypeDataServices, |
| | 0 | 56 | | orderExtraExpenseDataServices: orderExtraExpenseDataServices, |
| | 0 | 57 | | statusTransitionDataServices: statusTransitionDataServices) |
| | | 58 | | { |
| | 0 | 59 | | _httpClientFactory = httpClientFactory; |
| | 0 | 60 | | _emailService = emailService; |
| | 0 | 61 | | _ozonClientServices = ozonClientServices; |
| | 0 | 62 | | _cancellationService = cancellationService; |
| | 0 | 63 | | } |
| | | 64 | | |
| | 0 | 65 | | protected override TransactionConfig GetTransactionConfig() => new() |
| | 0 | 66 | | { |
| | 0 | 67 | | TransactionType = TransactionType.Cancelled, |
| | 0 | 68 | | PrimaryStatusName = "Отменен", |
| | 0 | 69 | | ViewName = "CreateCancelledTransaction", |
| | 0 | 70 | | RequiredSourceStatuses = new List<string> { "Заказан поставщику" }, |
| | 0 | 71 | | IncludeCancelledOrders = false, |
| | 0 | 72 | | // Стандартный фильтр исключает заказы с AppStatus="Не указан" и статусом Ozon "Отменён" — |
| | 0 | 73 | | // но именно такие заказы (уже отменённые на маркетплейсе, ещё не отражённые у нас) и есть |
| | 0 | 74 | | // основной кейс транзакции "Отменен". Допустимые исходные статусы уже ограничены StatusTransition. |
| | 0 | 75 | | OrderFilter = order => order.Status != "Отменен покупателем", |
| | 0 | 76 | | CreateTransactionMethod = (tm, orders, userName, createAt, comment) => |
| | 0 | 77 | | tm.CreateCancelledTransaction(orders, userName, createAt, comment), |
| | 0 | 78 | | ConfigureViewModelAsync = LoadOzonCancelReasonsAsync |
| | 0 | 79 | | }; |
| | | 80 | | |
| | | 81 | | public Task<IActionResult> CreateCancelledTransaction(string ids, int page) |
| | 0 | 82 | | => CreateTransactionBase(ids, page); |
| | | 83 | | |
| | | 84 | | [HttpPost] |
| | | 85 | | [ValidateAntiForgeryToken] |
| | | 86 | | public Task<IActionResult> CreateCancelledTransaction( |
| | | 87 | | List<Order> orders, string userName, string? comment, |
| | | 88 | | int page, string? deletedOrders, Dictionary<int, string?>? orderSupplierMap) |
| | 0 | 89 | | => CreateTransactionPostBase(orders, userName, comment, page, deletedOrders, orderSupplierMap); |
| | | 90 | | |
| | | 91 | | protected override string? GetPostTransactionSuccessAppendix() => |
| | 0 | 92 | | BuildOzonCancelSuccessHtml(_ozonCancelSuccessEntries); |
| | | 93 | | |
| | | 94 | | protected override async Task<string?> ExecutePreTransactionAsync(List<Order> orders) |
| | | 95 | | { |
| | 0 | 96 | | _ozonCancelSuccessEntries.Clear(); |
| | 0 | 97 | | var cancelRequests = ParseOzonCancelRequestsFromForm(); |
| | 0 | 98 | | if (cancelRequests.Count == 0) |
| | 0 | 99 | | return null; |
| | | 100 | | |
| | 0 | 101 | | await EnsureOzonClientsResolvedAsync(orders); |
| | 0 | 102 | | var ordersById = orders.ToDictionary(o => o.Id); |
| | 0 | 103 | | var errors = new List<string>(); |
| | | 104 | | |
| | 0 | 105 | | foreach (var request in cancelRequests) |
| | | 106 | | { |
| | 0 | 107 | | if (!ordersById.TryGetValue(request.OrderId, out var order)) |
| | | 108 | | { |
| | 0 | 109 | | errors.Add($"Заказ #{request.OrderId} не найден в транзакции."); |
| | 0 | 110 | | continue; |
| | | 111 | | } |
| | | 112 | | |
| | 0 | 113 | | if (!await IsOzonMarketplaceOrderAsync(order)) |
| | | 114 | | continue; |
| | | 115 | | |
| | 0 | 116 | | if (string.IsNullOrWhiteSpace(order.ShipmentNumber)) |
| | | 117 | | { |
| | 0 | 118 | | errors.Add($"Заказ {order.ShipmentNumber ?? "#" + order.Id}: нет номера отправления."); |
| | 0 | 119 | | continue; |
| | | 120 | | } |
| | | 121 | | |
| | 0 | 122 | | var ozonClientId = ResolveOzonClientId(order); |
| | 0 | 123 | | if (!ozonClientId.HasValue) |
| | | 124 | | { |
| | 0 | 125 | | errors.Add($"Заказ {order.ShipmentNumber}: не указан клиент Ozon."); |
| | 0 | 126 | | continue; |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | if (request.ReasonId <= 0) |
| | | 130 | | { |
| | 0 | 131 | | errors.Add($"Заказ {order.ShipmentNumber}: выберите причину отмены Ozon."); |
| | 0 | 132 | | continue; |
| | | 133 | | } |
| | | 134 | | |
| | 0 | 135 | | if (request.ReasonId == OzonOrderCancelReasonsInfo.ReasonRequiresMessageId && |
| | 0 | 136 | | string.IsNullOrWhiteSpace(request.ReasonMessage)) |
| | | 137 | | { |
| | 0 | 138 | | errors.Add( |
| | 0 | 139 | | $"Заказ {order.ShipmentNumber}: для причины «Другое (вина продавца)» укажите комментарий."); |
| | 0 | 140 | | continue; |
| | | 141 | | } |
| | | 142 | | |
| | | 143 | | try |
| | | 144 | | { |
| | 0 | 145 | | var ozonClient = await _ozonClientServices.GetOzonClientAsync(ozonClientId.Value); |
| | 0 | 146 | | if (ozonClient == null) |
| | | 147 | | { |
| | 0 | 148 | | errors.Add($"Заказ {order.ShipmentNumber}: клиент Ozon не найден."); |
| | 0 | 149 | | continue; |
| | | 150 | | } |
| | | 151 | | |
| | 0 | 152 | | var clientId = ozonClient.DecryptClientId; |
| | 0 | 153 | | var apiKey = ozonClient.DecryptApiKey; |
| | | 154 | | |
| | 0 | 155 | | if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(apiKey)) |
| | | 156 | | { |
| | 0 | 157 | | errors.Add($"Заказ {order.ShipmentNumber}: не настроены учётные данные Ozon API."); |
| | 0 | 158 | | continue; |
| | | 159 | | } |
| | | 160 | | |
| | 0 | 161 | | var apiManager = new OzonApiDataManager(_httpClientFactory, _emailService, clientId, apiKey); |
| | 0 | 162 | | var cancelled = await apiManager.CancelFbsPostingAsync( |
| | 0 | 163 | | order.ShipmentNumber, |
| | 0 | 164 | | request.ReasonId, |
| | 0 | 165 | | request.ReasonMessage); |
| | | 166 | | |
| | 0 | 167 | | if (!cancelled) |
| | | 168 | | { |
| | 0 | 169 | | errors.Add($"Заказ {order.ShipmentNumber}: Ozon не подтвердил отмену отправления."); |
| | 0 | 170 | | continue; |
| | | 171 | | } |
| | | 172 | | |
| | 0 | 173 | | await _cancellationService.RecordAsync(ozonClient.Id, order.ShipmentNumber.Trim(), request.ReasonId, |
| | 0 | 174 | | request.ReasonTitle, request.ReasonMessage, null, DateTime.UtcNow, "Manual", [order.Id]); |
| | | 175 | | |
| | 0 | 176 | | _ozonCancelSuccessEntries.Add(new OzonCancelSuccessEntry( |
| | 0 | 177 | | order.ShipmentNumber.Trim(), |
| | 0 | 178 | | request.ReasonTitle, |
| | 0 | 179 | | request.ReasonMessage)); |
| | 0 | 180 | | } |
| | 0 | 181 | | catch (Exception ex) |
| | | 182 | | { |
| | 0 | 183 | | errors.Add($"Заказ {order.ShipmentNumber}: {ex.Message}"); |
| | 0 | 184 | | } |
| | 0 | 185 | | } |
| | | 186 | | |
| | 0 | 187 | | return errors.Count > 0 ? string.Join("<br/>", errors) : null; |
| | 0 | 188 | | } |
| | | 189 | | |
| | | 190 | | private static string? BuildOzonCancelSuccessHtml(IReadOnlyList<OzonCancelSuccessEntry> entries) |
| | | 191 | | { |
| | 0 | 192 | | if (entries == null || entries.Count == 0) |
| | 0 | 193 | | return null; |
| | | 194 | | |
| | 0 | 195 | | var sb = new StringBuilder(); |
| | 0 | 196 | | sb.Append("<div class='tx-result-extra ozon-cancel-success-summary'>"); |
| | 0 | 197 | | sb.Append("<div class='small fw-semibold mb-1'><i class='fas fa-store me-1'></i>Отмена в Ozon</div>"); |
| | 0 | 198 | | sb.Append("<ul class='small mb-0 ps-3' style='list-style: disc;'>"); |
| | 0 | 199 | | foreach (var entry in entries) |
| | | 200 | | { |
| | 0 | 201 | | sb.Append("<li>"); |
| | 0 | 202 | | sb.Append(WebUtility.HtmlEncode(entry.ShipmentNumber)); |
| | 0 | 203 | | if (!string.IsNullOrWhiteSpace(entry.ReasonTitle)) |
| | | 204 | | { |
| | 0 | 205 | | sb.Append(" — "); |
| | 0 | 206 | | sb.Append(WebUtility.HtmlEncode(entry.ReasonTitle)); |
| | | 207 | | } |
| | | 208 | | |
| | 0 | 209 | | if (!string.IsNullOrWhiteSpace(entry.ReasonMessage)) |
| | | 210 | | { |
| | 0 | 211 | | sb.Append(" ("); |
| | 0 | 212 | | sb.Append(WebUtility.HtmlEncode(entry.ReasonMessage)); |
| | 0 | 213 | | sb.Append(')'); |
| | | 214 | | } |
| | | 215 | | |
| | 0 | 216 | | sb.Append("</li>"); |
| | | 217 | | } |
| | | 218 | | |
| | 0 | 219 | | sb.Append("</ul></div>"); |
| | 0 | 220 | | return sb.ToString(); |
| | | 221 | | } |
| | | 222 | | |
| | | 223 | | private async Task LoadOzonCancelReasonsAsync(MultiplayEditOrderViewModel viewModel) |
| | | 224 | | { |
| | 0 | 225 | | if (viewModel.Orders == null || !viewModel.Orders.Any()) |
| | 0 | 226 | | return; |
| | | 227 | | |
| | 0 | 228 | | await EnsureOzonClientsResolvedAsync(viewModel.Orders); |
| | | 229 | | |
| | 0 | 230 | | var reasonsByOrderId = new Dictionary<int, OzonOrderCancelReasonsInfo>(); |
| | | 231 | | |
| | 0 | 232 | | foreach (var order in viewModel.Orders) |
| | | 233 | | { |
| | 0 | 234 | | if (!await IsOzonMarketplaceOrderAsync(order)) |
| | | 235 | | continue; |
| | | 236 | | |
| | 0 | 237 | | if (string.IsNullOrWhiteSpace(order.ShipmentNumber)) |
| | | 238 | | { |
| | 0 | 239 | | reasonsByOrderId[order.Id] = new OzonOrderCancelReasonsInfo |
| | 0 | 240 | | { |
| | 0 | 241 | | ErrorMessage = "Нет номера отправления" |
| | 0 | 242 | | }; |
| | 0 | 243 | | continue; |
| | | 244 | | } |
| | | 245 | | |
| | 0 | 246 | | if (!ResolveOzonClientId(order).HasValue) |
| | | 247 | | { |
| | 0 | 248 | | reasonsByOrderId[order.Id] = new OzonOrderCancelReasonsInfo |
| | 0 | 249 | | { |
| | 0 | 250 | | PostingNumber = order.ShipmentNumber.Trim(), |
| | 0 | 251 | | ErrorMessage = "Не указан клиент Ozon" |
| | 0 | 252 | | }; |
| | 0 | 253 | | continue; |
| | | 254 | | } |
| | | 255 | | |
| | 0 | 256 | | reasonsByOrderId[order.Id] = new OzonOrderCancelReasonsInfo |
| | 0 | 257 | | { |
| | 0 | 258 | | PostingNumber = order.ShipmentNumber.Trim() |
| | 0 | 259 | | }; |
| | 0 | 260 | | } |
| | | 261 | | |
| | 0 | 262 | | var clientGroups = viewModel.Orders |
| | 0 | 263 | | .Where(o => reasonsByOrderId.ContainsKey(o.Id)) |
| | 0 | 264 | | .Select(o => new { Order = o, ClientId = ResolveOzonClientId(o) }) |
| | 0 | 265 | | .Where(x => x.ClientId.HasValue && !string.IsNullOrWhiteSpace(x.Order.ShipmentNumber)) |
| | 0 | 266 | | .GroupBy(x => x.ClientId!.Value, x => x.Order); |
| | | 267 | | |
| | 0 | 268 | | foreach (var clientGroup in clientGroups) |
| | | 269 | | { |
| | | 270 | | try |
| | | 271 | | { |
| | 0 | 272 | | var ozonClient = await _ozonClientServices.GetOzonClientAsync(clientGroup.Key); |
| | 0 | 273 | | if (ozonClient == null) |
| | | 274 | | { |
| | 0 | 275 | | foreach (var order in clientGroup) |
| | 0 | 276 | | reasonsByOrderId[order.Id].ErrorMessage = "Клиент Ozon не найден"; |
| | 0 | 277 | | continue; |
| | | 278 | | } |
| | | 279 | | |
| | 0 | 280 | | var clientId = ozonClient.DecryptClientId; |
| | 0 | 281 | | var apiKey = ozonClient.DecryptApiKey; |
| | | 282 | | |
| | 0 | 283 | | if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(apiKey)) |
| | | 284 | | { |
| | 0 | 285 | | foreach (var order in clientGroup) |
| | | 286 | | { |
| | 0 | 287 | | reasonsByOrderId[order.Id].ErrorMessage = "Не настроены Client-Id или Api-Key Ozon"; |
| | | 288 | | } |
| | | 289 | | |
| | 0 | 290 | | continue; |
| | | 291 | | } |
| | | 292 | | |
| | 0 | 293 | | var apiManager = new OzonApiDataManager(_httpClientFactory, _emailService, clientId, apiKey); |
| | 0 | 294 | | var postingNumbers = clientGroup |
| | 0 | 295 | | .Select(o => o.ShipmentNumber!.Trim()) |
| | 0 | 296 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 297 | | .ToList(); |
| | | 298 | | |
| | 0 | 299 | | var response = await apiManager.GetFbsCancelReasonsAsync(postingNumbers); |
| | 0 | 300 | | var reasonsByPosting = (response?.Result ?? new List<FbsCancelReasonPostingResult>()) |
| | 0 | 301 | | .Where(r => !string.IsNullOrWhiteSpace(r.PostingNumber)) |
| | 0 | 302 | | .ToDictionary( |
| | 0 | 303 | | r => r.PostingNumber!, |
| | 0 | 304 | | r => r.Reasons ?? new List<FbsCancelReasonItem>(), |
| | 0 | 305 | | StringComparer.OrdinalIgnoreCase); |
| | | 306 | | |
| | 0 | 307 | | foreach (var order in clientGroup) |
| | | 308 | | { |
| | 0 | 309 | | var posting = order.ShipmentNumber!.Trim(); |
| | 0 | 310 | | if (!reasonsByPosting.TryGetValue(posting, out var cancelReasons) || cancelReasons.Count == 0) |
| | | 311 | | { |
| | 0 | 312 | | reasonsByOrderId[order.Id].ErrorMessage = |
| | 0 | 313 | | "Ozon не вернул причины отмены для этого отправления"; |
| | 0 | 314 | | continue; |
| | | 315 | | } |
| | | 316 | | |
| | 0 | 317 | | reasonsByOrderId[order.Id].Reasons = cancelReasons |
| | 0 | 318 | | .Select(r => new OzonCancelReasonOption |
| | 0 | 319 | | { |
| | 0 | 320 | | Id = r.Id, |
| | 0 | 321 | | Title = r.Title ?? string.Empty, |
| | 0 | 322 | | TypeId = r.TypeId |
| | 0 | 323 | | }) |
| | 0 | 324 | | .ToList(); |
| | | 325 | | } |
| | 0 | 326 | | } |
| | 0 | 327 | | catch (Exception ex) |
| | | 328 | | { |
| | 0 | 329 | | foreach (var order in clientGroup) |
| | 0 | 330 | | reasonsByOrderId[order.Id].ErrorMessage = ex.Message; |
| | 0 | 331 | | } |
| | 0 | 332 | | } |
| | | 333 | | |
| | 0 | 334 | | viewModel.OzonPostingCancelReasons = reasonsByOrderId; |
| | 0 | 335 | | } |
| | | 336 | | |
| | | 337 | | private List<OzonCancelFormRequest> ParseOzonCancelRequestsFromForm() |
| | | 338 | | { |
| | 0 | 339 | | var result = new List<OzonCancelFormRequest>(); |
| | 0 | 340 | | var checkedOrderIds = new HashSet<int>(); |
| | | 341 | | |
| | 0 | 342 | | foreach (var key in Request.Form.Keys) |
| | | 343 | | { |
| | 0 | 344 | | if (!key.StartsWith("CancelInOzon[", StringComparison.Ordinal) || !key.EndsWith(']')) |
| | | 345 | | continue; |
| | | 346 | | |
| | 0 | 347 | | var idPart = key["CancelInOzon[".Length..^1]; |
| | 0 | 348 | | if (!int.TryParse(idPart, out var orderId)) |
| | | 349 | | continue; |
| | | 350 | | |
| | 0 | 351 | | var value = Request.Form[key].FirstOrDefault(); |
| | 0 | 352 | | if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) || |
| | 0 | 353 | | string.Equals(value, "on", StringComparison.OrdinalIgnoreCase)) |
| | | 354 | | { |
| | 0 | 355 | | checkedOrderIds.Add(orderId); |
| | | 356 | | } |
| | | 357 | | } |
| | | 358 | | |
| | 0 | 359 | | foreach (var orderId in checkedOrderIds) |
| | | 360 | | { |
| | 0 | 361 | | long reasonId = 0; |
| | 0 | 362 | | var reasonKey = $"OzonCancelReasonId[{orderId}]"; |
| | 0 | 363 | | if (Request.Form.ContainsKey(reasonKey)) |
| | 0 | 364 | | long.TryParse(Request.Form[reasonKey].FirstOrDefault(), out reasonId); |
| | | 365 | | |
| | 0 | 366 | | string? message = null; |
| | 0 | 367 | | var messageKey = $"OzonCancelReasonMessage[{orderId}]"; |
| | 0 | 368 | | if (Request.Form.ContainsKey(messageKey)) |
| | 0 | 369 | | message = Request.Form[messageKey].FirstOrDefault(); |
| | | 370 | | |
| | 0 | 371 | | string? reasonTitle = null; |
| | 0 | 372 | | var titleKey = $"OzonCancelReasonTitle[{orderId}]"; |
| | 0 | 373 | | if (Request.Form.ContainsKey(titleKey)) |
| | 0 | 374 | | reasonTitle = Request.Form[titleKey].FirstOrDefault(); |
| | | 375 | | |
| | 0 | 376 | | result.Add(new OzonCancelFormRequest(orderId, reasonId, message, reasonTitle)); |
| | | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | return result; |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | /// <summary> |
| | | 383 | | /// Клиент Ozon из FK, навигации (в т.ч. скрытое поле формы) или данных заказа в БД. |
| | | 384 | | /// </summary> |
| | | 385 | | private async Task<bool> IsOzonMarketplaceOrderAsync(Order order) |
| | | 386 | | { |
| | 0 | 387 | | if (order.OzonClient?.ClientType == ClientType.OZON) |
| | 0 | 388 | | return true; |
| | | 389 | | |
| | 0 | 390 | | var clientId = ResolveOzonClientId(order); |
| | 0 | 391 | | if (!clientId.HasValue) |
| | 0 | 392 | | return false; |
| | | 393 | | |
| | | 394 | | try |
| | | 395 | | { |
| | 0 | 396 | | var client = await _ozonClientServices.GetOzonClientAsync(clientId.Value); |
| | 0 | 397 | | if (client == null) |
| | 0 | 398 | | return false; |
| | | 399 | | |
| | 0 | 400 | | order.OzonClient ??= client; |
| | 0 | 401 | | return client.ClientType == ClientType.OZON; |
| | | 402 | | } |
| | 0 | 403 | | catch |
| | | 404 | | { |
| | 0 | 405 | | return false; |
| | | 406 | | } |
| | 0 | 407 | | } |
| | | 408 | | |
| | | 409 | | private static int? ResolveOzonClientId(Order order) |
| | | 410 | | { |
| | 0 | 411 | | if (order.OzonClientId is > 0) |
| | 0 | 412 | | return order.OzonClientId; |
| | | 413 | | |
| | 0 | 414 | | if (order.OzonClient?.Id is > 0) |
| | 0 | 415 | | return order.OzonClient.Id; |
| | | 416 | | |
| | 0 | 417 | | return null; |
| | | 418 | | } |
| | | 419 | | |
| | | 420 | | private async Task EnsureOzonClientsResolvedAsync(IEnumerable<Order> orders) |
| | | 421 | | { |
| | 0 | 422 | | var orderList = orders.ToList(); |
| | 0 | 423 | | if (orderList.Count == 0) |
| | 0 | 424 | | return; |
| | | 425 | | |
| | 0 | 426 | | foreach (var order in orderList) |
| | | 427 | | { |
| | 0 | 428 | | var resolved = ResolveOzonClientId(order); |
| | 0 | 429 | | if (resolved.HasValue) |
| | 0 | 430 | | order.OzonClientId = resolved; |
| | | 431 | | } |
| | | 432 | | |
| | 0 | 433 | | var missingIds = orderList |
| | 0 | 434 | | .Where(o => !ResolveOzonClientId(o).HasValue) |
| | 0 | 435 | | .Select(o => o.Id) |
| | 0 | 436 | | .Distinct() |
| | 0 | 437 | | .ToList(); |
| | | 438 | | |
| | 0 | 439 | | if (missingIds.Count == 0) |
| | 0 | 440 | | return; |
| | | 441 | | |
| | 0 | 442 | | var dbOrders = await Context.Orders |
| | 0 | 443 | | .AsNoTracking() |
| | 0 | 444 | | .Include(o => o.OzonClient) |
| | 0 | 445 | | .Where(o => missingIds.Contains(o.Id)) |
| | 0 | 446 | | .ToListAsync(); |
| | | 447 | | |
| | 0 | 448 | | var dbById = dbOrders.ToDictionary(o => o.Id); |
| | 0 | 449 | | foreach (var order in orderList.Where(o => !ResolveOzonClientId(o).HasValue)) |
| | | 450 | | { |
| | 0 | 451 | | if (!dbById.TryGetValue(order.Id, out var dbOrder)) |
| | | 452 | | continue; |
| | | 453 | | |
| | 0 | 454 | | ApplyOzonClientFromSource(order, dbOrder); |
| | | 455 | | } |
| | | 456 | | |
| | 0 | 457 | | var stillMissing = orderList.Where(o => !ResolveOzonClientId(o).HasValue).ToList(); |
| | 0 | 458 | | if (stillMissing.Count == 0) |
| | 0 | 459 | | return; |
| | | 460 | | |
| | 0 | 461 | | var shipmentIds = stillMissing |
| | 0 | 462 | | .Where(o => o.ShipmentId.HasValue) |
| | 0 | 463 | | .Select(o => o.ShipmentId!.Value) |
| | 0 | 464 | | .Distinct() |
| | 0 | 465 | | .ToList(); |
| | | 466 | | |
| | 0 | 467 | | if (shipmentIds.Count > 0) |
| | | 468 | | { |
| | 0 | 469 | | var clientByShipment = await Context.Orders |
| | 0 | 470 | | .AsNoTracking() |
| | 0 | 471 | | .Where(o => o.ShipmentId.HasValue && |
| | 0 | 472 | | shipmentIds.Contains(o.ShipmentId.Value) && |
| | 0 | 473 | | o.OzonClientId != null) |
| | 0 | 474 | | .GroupBy(o => o.ShipmentId!.Value) |
| | 0 | 475 | | .Select(g => new { ShipmentId = g.Key, OzonClientId = g.Select(x => x.OzonClientId).First() }) |
| | 0 | 476 | | .ToDictionaryAsync(x => x.ShipmentId, x => x.OzonClientId!.Value); |
| | | 477 | | |
| | 0 | 478 | | foreach (var order in stillMissing.Where(o => o.ShipmentId.HasValue)) |
| | | 479 | | { |
| | 0 | 480 | | if (clientByShipment.TryGetValue(order.ShipmentId!.Value, out var clientId)) |
| | 0 | 481 | | order.OzonClientId = clientId; |
| | | 482 | | } |
| | | 483 | | } |
| | | 484 | | |
| | 0 | 485 | | stillMissing = orderList.Where(o => !ResolveOzonClientId(o).HasValue).ToList(); |
| | 0 | 486 | | var shipmentNumbers = stillMissing |
| | 0 | 487 | | .Select(o => o.ShipmentNumber?.Trim()) |
| | 0 | 488 | | .Where(n => !string.IsNullOrWhiteSpace(n)) |
| | 0 | 489 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 490 | | .ToList(); |
| | | 491 | | |
| | 0 | 492 | | if (shipmentNumbers.Count == 0) |
| | 0 | 493 | | return; |
| | | 494 | | |
| | 0 | 495 | | var clientByPosting = await Context.Orders |
| | 0 | 496 | | .AsNoTracking() |
| | 0 | 497 | | .Where(o => o.ShipmentNumber != null && |
| | 0 | 498 | | o.OzonClientId != null && |
| | 0 | 499 | | shipmentNumbers.Contains(o.ShipmentNumber)) |
| | 0 | 500 | | .GroupBy(o => o.ShipmentNumber!) |
| | 0 | 501 | | .Select(g => new { ShipmentNumber = g.Key, OzonClientId = g.Select(x => x.OzonClientId).First() }) |
| | 0 | 502 | | .ToDictionaryAsync(x => x.ShipmentNumber, x => x.OzonClientId!.Value, StringComparer.OrdinalIgnoreCase); |
| | | 503 | | |
| | 0 | 504 | | foreach (var order in stillMissing) |
| | | 505 | | { |
| | 0 | 506 | | var posting = order.ShipmentNumber?.Trim(); |
| | 0 | 507 | | if (string.IsNullOrWhiteSpace(posting)) |
| | | 508 | | continue; |
| | | 509 | | |
| | 0 | 510 | | if (clientByPosting.TryGetValue(posting, out var clientId)) |
| | 0 | 511 | | order.OzonClientId = clientId; |
| | | 512 | | } |
| | 0 | 513 | | } |
| | | 514 | | |
| | | 515 | | private static void ApplyOzonClientFromSource(Order target, Order source) |
| | | 516 | | { |
| | 0 | 517 | | if (source.OzonClientId is > 0) |
| | 0 | 518 | | target.OzonClientId = source.OzonClientId; |
| | 0 | 519 | | else if (source.OzonClient?.Id is > 0) |
| | 0 | 520 | | target.OzonClientId = source.OzonClient.Id; |
| | | 521 | | |
| | 0 | 522 | | if (target.OzonClient == null && source.OzonClient != null) |
| | 0 | 523 | | target.OzonClient = source.OzonClient; |
| | 0 | 524 | | } |
| | | 525 | | |
| | 0 | 526 | | private sealed record OzonCancelSuccessEntry(string ShipmentNumber, string? ReasonTitle, string? ReasonMessage); |
| | | 527 | | |
| | 0 | 528 | | private sealed record OzonCancelFormRequest(int OrderId, long ReasonId, string? ReasonMessage, string? ReasonTitle); |
| | | 529 | | } |