| | | 1 | | using Microsoft.AspNetCore.Authorization; |
| | | 2 | | using Microsoft.AspNetCore.Identity; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.AspNetCore.SignalR; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | using Microsoft.Extensions.Caching.Memory; |
| | | 7 | | using Microsoft.Extensions.DependencyInjection; |
| | | 8 | | using Newtonsoft.Json; |
| | | 9 | | using OzonDomains; |
| | | 10 | | using OzonDomains.Models; |
| | | 11 | | using Services.ApiServices.OzonApi; |
| | | 12 | | using Services.ApiServices.OzonApi.Filters; |
| | | 13 | | using OzonOrdersWeb.Areas.Studio2.ViewModels.OrderHistory; |
| | | 14 | | using OzonOrdersWeb.WebServices.Orders; |
| | | 15 | | using OzonOrdersWeb.WebServices.Orders.Grid; |
| | | 16 | | using OzonOrdersWeb.Authorization; |
| | | 17 | | using OzonRepositories.Context; |
| | | 18 | | using OzonRepositories.Context.Identity; |
| | | 19 | | using Services.Authorization.Services; |
| | | 20 | | using Services.DataServices; |
| | | 21 | | using Services.DataServices.OrderRollback; |
| | | 22 | | using OzonDomains.Models.Authorization.Enums; |
| | | 23 | | using OzonDomains.Models.SupplierStatuses; |
| | | 24 | | using Services.ParserServices.HelpDictEnum; |
| | | 25 | | using Services.SignalRServices; |
| | | 26 | | using Services.BitrixStockServices; |
| | | 27 | | using Services.ApiServices._1CApi.Models; |
| | | 28 | | using System.Collections.Concurrent; |
| | | 29 | | using System.Security.Claims; |
| | | 30 | | using System.Text.Json; |
| | | 31 | | using OzonRepositories.Data; |
| | | 32 | | using Services.OzonHandoverServices; |
| | | 33 | | using Services.LabelServices; |
| | | 34 | | |
| | | 35 | | [Authorize(Roles = "User,Admin")] |
| | | 36 | | [Area("Studio2")] |
| | | 37 | | public partial class OrderHistoryController : Controller |
| | | 38 | | { |
| | | 39 | | private readonly IOrderHistoryDataService _orderHistoryService; |
| | | 40 | | private readonly IOrderHistoryOneCPostingService _oneCPostingService; |
| | | 41 | | private readonly OrdersDataServices _ordersDataServices; |
| | | 42 | | private readonly TransactionDataServices _transactionDataServices; |
| | | 43 | | private readonly OzonApiDataManager _ozonApiDataManager; |
| | | 44 | | private readonly OzonClientServices _ozonClientServices; |
| | | 45 | | private readonly IHubContext<OrderHistoryHub> _hubContext; |
| | | 46 | | private readonly IMemoryCache _memoryCache; |
| | | 47 | | private readonly IServiceScopeFactory _scopeFactory; |
| | | 48 | | private readonly IBitrixStockSyncArticleHistoryService _bitrixSyncArticleHistoryService; |
| | | 49 | | private readonly IOrdersGridFeedPriceService _feedPriceService; |
| | | 50 | | private readonly ApplicationDbContext _context; |
| | | 51 | | private readonly IDataScopeService _dataScopeService; |
| | | 52 | | private readonly IScopeFilterValuesService _scopeFilterValuesService; |
| | | 53 | | private readonly IOrderHistoryRollbackService _rollbackService; |
| | | 54 | | private readonly UserManager<CustomIdentityUser> _userManager; |
| | | 55 | | private readonly IOzonHandoverPhotoStorage _handoverPhotoStorage; |
| | | 56 | | |
| | | 57 | | private const string ShipmentTotalsCacheKeyPrefix = "shipment_totals_v1_order_"; |
| | 0 | 58 | | private static readonly TimeSpan ShipmentTotalsCacheAbsoluteExpiration = TimeSpan.FromMinutes(20); |
| | 0 | 59 | | private static readonly TimeSpan ShipmentTotalsCacheSlidingExpiration = TimeSpan.FromMinutes(5); |
| | | 60 | | |
| | 0 | 61 | | public OrderHistoryController( |
| | 0 | 62 | | IOrderHistoryDataService orderHistoryService, |
| | 0 | 63 | | IOrderHistoryOneCPostingService oneCPostingService, |
| | 0 | 64 | | OrdersDataServices ordersDataServices, |
| | 0 | 65 | | TransactionDataServices transactionDataServices, |
| | 0 | 66 | | OzonApiDataManager ozonApiDataManager, |
| | 0 | 67 | | OzonClientServices ozonClientServices, |
| | 0 | 68 | | IHubContext<OrderHistoryHub> hubContext, |
| | 0 | 69 | | IMemoryCache memoryCache, |
| | 0 | 70 | | IServiceScopeFactory scopeFactory, |
| | 0 | 71 | | IBitrixStockSyncArticleHistoryService bitrixSyncArticleHistoryService, |
| | 0 | 72 | | IOrdersGridFeedPriceService feedPriceService, |
| | 0 | 73 | | ApplicationDbContext context, |
| | 0 | 74 | | IDataScopeService dataScopeService, |
| | 0 | 75 | | IScopeFilterValuesService scopeFilterValuesService, |
| | 0 | 76 | | IOrderHistoryRollbackService rollbackService, |
| | 0 | 77 | | UserManager<CustomIdentityUser> userManager, |
| | 0 | 78 | | IOzonHandoverPhotoStorage handoverPhotoStorage) |
| | | 79 | | { |
| | 0 | 80 | | _orderHistoryService = orderHistoryService; |
| | 0 | 81 | | _oneCPostingService = oneCPostingService; |
| | 0 | 82 | | _ordersDataServices = ordersDataServices; |
| | 0 | 83 | | _transactionDataServices = transactionDataServices; |
| | 0 | 84 | | _ozonApiDataManager = ozonApiDataManager; |
| | 0 | 85 | | _ozonClientServices = ozonClientServices; |
| | 0 | 86 | | _hubContext = hubContext; |
| | 0 | 87 | | _memoryCache = memoryCache; |
| | 0 | 88 | | _scopeFactory = scopeFactory; |
| | 0 | 89 | | _bitrixSyncArticleHistoryService = bitrixSyncArticleHistoryService; |
| | 0 | 90 | | _feedPriceService = feedPriceService; |
| | 0 | 91 | | _context = context; |
| | 0 | 92 | | _dataScopeService = dataScopeService; |
| | 0 | 93 | | _scopeFilterValuesService = scopeFilterValuesService; |
| | 0 | 94 | | _rollbackService = rollbackService; |
| | 0 | 95 | | _userManager = userManager; |
| | 0 | 96 | | _handoverPhotoStorage = handoverPhotoStorage; |
| | 0 | 97 | | } |
| | | 98 | | |
| | | 99 | | public async Task<IActionResult> Index() |
| | | 100 | | { |
| | 0 | 101 | | var recentChanges = await _orderHistoryService.GetRecentChangesAsync(100); |
| | 0 | 102 | | return View(recentChanges); |
| | 0 | 103 | | } |
| | | 104 | | |
| | | 105 | | [HttpGet] |
| | | 106 | | public async Task<IActionResult> GetRecentChanges() |
| | | 107 | | { |
| | 0 | 108 | | var changes = await _orderHistoryService.GetRecentChangesAsync(50); |
| | 0 | 109 | | return Ok(changes); |
| | 0 | 110 | | } |
| | | 111 | | |
| | | 112 | | [HttpGet] |
| | | 113 | | public async Task<IActionResult> GetHandoverPhoto(int orderId, long photoId, CancellationToken ct) |
| | | 114 | | { |
| | 0 | 115 | | var photo = await _context.OzonHandoverActItemPhotos |
| | 0 | 116 | | .AsNoTracking() |
| | 0 | 117 | | .Where(p => p.Id == photoId && p.ActItem != null && p.ActItem.OrderId == orderId) |
| | 0 | 118 | | .Select(p => new { p.StoragePath, p.ContentType }) |
| | 0 | 119 | | .FirstOrDefaultAsync(ct); |
| | 0 | 120 | | if (photo == null) |
| | 0 | 121 | | return NotFound(); |
| | | 122 | | |
| | | 123 | | try |
| | | 124 | | { |
| | 0 | 125 | | var stream = await _handoverPhotoStorage.OpenReadAsync(photo.StoragePath, ct).ConfigureAwait(false); |
| | 0 | 126 | | return File(stream, photo.ContentType ?? "image/jpeg", enableRangeProcessing: true); |
| | | 127 | | } |
| | 0 | 128 | | catch (FileNotFoundException) |
| | | 129 | | { |
| | 0 | 130 | | return NotFound(); |
| | | 131 | | } |
| | 0 | 132 | | } |
| | | 133 | | |
| | | 134 | | [HttpGet] |
| | | 135 | | public async Task<IActionResult> GetOrderHistory(int orderId) |
| | | 136 | | { |
| | | 137 | | // Независимы от order/histories — стартуют сразу, каждый в своём scope (свой |
| | | 138 | | // ApplicationDbContext), чтобы безопасно выполняться параллельно с загрузкой истории ниже. |
| | 0 | 139 | | var shipmentTotalsHistoryTask = LoadShipmentTotalsHistoryInScopeAsync(orderId); |
| | 0 | 140 | | var oneCPostingsTask = LoadOneCPostingsInScopeAsync(orderId); |
| | 0 | 141 | | var handoverItemsTask = LoadHandoverItemsInScopeAsync(orderId); |
| | 0 | 142 | | var labelPrintsTask = LoadLabelPrintsInScopeAsync(orderId); |
| | | 143 | | |
| | 0 | 144 | | var histories = await _orderHistoryService.GetByOrderIdAsync(orderId) ?? new List<OrderHistory>(); |
| | | 145 | | |
| | 0 | 146 | | var order = histories.FirstOrDefault()?.Order; |
| | 0 | 147 | | if (order == null) |
| | | 148 | | { |
| | 0 | 149 | | order = await _ordersDataServices.GetAsyncNoTracking(orderId).ConfigureAwait(false); |
| | 0 | 150 | | if (order == null) |
| | | 151 | | { |
| | | 152 | | // Не оставляем уже запущенные задачи "висящими" без await. |
| | 0 | 153 | | await Task.WhenAll(shipmentTotalsHistoryTask, oneCPostingsTask, handoverItemsTask, labelPrintsTask).Conf |
| | 0 | 154 | | return NotFound($"Заказ {orderId} не найден."); |
| | | 155 | | } |
| | | 156 | | } |
| | | 157 | | |
| | 0 | 158 | | var transactionIds = CollectTransactionIds(order, histories); |
| | 0 | 159 | | var transactionsTask = LoadTransactionsInScopeAsync(transactionIds); |
| | 0 | 160 | | var userProfilesTask = BuildHistoryUserProfilesAsync(histories); |
| | | 161 | | |
| | 0 | 162 | | await Task.WhenAll(transactionsTask, shipmentTotalsHistoryTask, oneCPostingsTask, userProfilesTask, handoverItem |
| | 0 | 163 | | .ConfigureAwait(false); |
| | | 164 | | |
| | 0 | 165 | | var transactions = transactionsTask.Result; |
| | 0 | 166 | | var shipmentTotalsHistory = shipmentTotalsHistoryTask.Result; |
| | 0 | 167 | | var oneCPostings = oneCPostingsTask.Result; |
| | 0 | 168 | | var userProfiles = userProfilesTask.Result; |
| | 0 | 169 | | var handoverItems = handoverItemsTask.Result; |
| | 0 | 170 | | var labelPrints = labelPrintsTask.Result; |
| | 0 | 171 | | var supplierStatusTimelineByHistoryId = await LoadSupplierStatusTimelineAsync(orderId, HttpContext.RequestAborte |
| | 0 | 172 | | var calculationSnapshots = await _context.OrderCalculationSnapshots.AsNoTracking() |
| | 0 | 173 | | .Where(x => x.OrderId == orderId) |
| | 0 | 174 | | .OrderByDescending(x => x.CapturedAt) |
| | 0 | 175 | | .ToListAsync(HttpContext.RequestAborted); |
| | 0 | 176 | | var quotationSummary = order.ProductInfoId is int quotationProductId |
| | 0 | 177 | | ? await _context.SupplierQuotationRequests.AsNoTracking() |
| | 0 | 178 | | .Where(x => x.ProductId == quotationProductId) |
| | 0 | 179 | | .GroupBy(_ => 1) |
| | 0 | 180 | | .Select(g => new { Requests = g.Count(), Offers = g.Sum(x => x.OffersCount) }) |
| | 0 | 181 | | .SingleOrDefaultAsync(HttpContext.RequestAborted) |
| | 0 | 182 | | : null; |
| | | 183 | | |
| | 0 | 184 | | var problems = await LoadOrderProblemsAsync(order, HttpContext.RequestAborted); |
| | | 185 | | |
| | 0 | 186 | | var viewModel = new OrderHistoryViewModel |
| | 0 | 187 | | { |
| | 0 | 188 | | OrderId = orderId, |
| | 0 | 189 | | Problems = problems, |
| | 0 | 190 | | ProductId = order.ProductInfoId, |
| | 0 | 191 | | QuotationRequestsCount = quotationSummary?.Requests ?? 0, |
| | 0 | 192 | | QuotationOffersCount = quotationSummary?.Offers ?? 0, |
| | 0 | 193 | | ShipmentNumber = order?.ShipmentNumber, |
| | 0 | 194 | | ProductName = order?.ProductName, |
| | 0 | 195 | | ProductImageUrl = order?.ProductInfo?.ImageUrl, |
| | 0 | 196 | | Article = order?.Article, |
| | 0 | 197 | | ClientName = order?.OzonClient?.Name, |
| | 0 | 198 | | SupplierStatusTimelineByHistoryId = supplierStatusTimelineByHistoryId, |
| | 0 | 199 | | Histories = histories |
| | | 200 | | .GroupBy(h => h.ChangedAt.Date) |
| | | 201 | | .OrderByDescending(g => g.Key) |
| | | 202 | | .ToDictionary(g => g.Key, g => g.ToList()), |
| | 0 | 203 | | Transactions = transactions, |
| | 0 | 204 | | // Начисления Ozon больше не грузятся синхронно в SSR — вкладка "Начисления Ozon" |
| | 0 | 205 | | // подгружает их лениво через GetShipmentTotals (см. order-history-finance.js). |
| | 0 | 206 | | FinanceOperations = new List<FinanceTransactionOperation>(), |
| | 0 | 207 | | FinanceTotals = null, |
| | 0 | 208 | | ShipmentTotalsHistory = shipmentTotalsHistory, |
| | 0 | 209 | | OneCPostings = oneCPostings, |
| | 0 | 210 | | HandoverItems = handoverItems, |
| | 0 | 211 | | LabelPrints = labelPrints, |
| | 0 | 212 | | UserProfiles = userProfiles, |
| | 0 | 213 | | CalculationSnapshotIdsByOperationId = calculationSnapshots |
| | | 214 | | .GroupBy(x => x.OperationId.ToString()) |
| | | 215 | | .ToDictionary(x => x.Key, x => x.First().Id, StringComparer.OrdinalIgnoreCase), |
| | 0 | 216 | | CalculationSnapshots = calculationSnapshots.Select(MapCalculationSnapshot).ToList() |
| | 0 | 217 | | }; |
| | | 218 | | |
| | 0 | 219 | | return View(viewModel); |
| | 0 | 220 | | } |
| | | 221 | | |
| | | 222 | | /// <summary>Проблемы одного заказа для панели на странице истории; сбой сбора не должен ломать страницу.</summary> |
| | | 223 | | private async Task<IReadOnlyList<OrderProblem>> LoadOrderProblemsAsync(Order order, CancellationToken cancellationTo |
| | | 224 | | { |
| | | 225 | | try |
| | | 226 | | { |
| | 0 | 227 | | var service = HttpContext.RequestServices.GetRequiredService<IOrderProblemInfoService>(); |
| | 0 | 228 | | await service.PopulateForOrdersAsync([order], cancellationToken); |
| | 0 | 229 | | return order.Problems ?? []; |
| | | 230 | | } |
| | 0 | 231 | | catch (Exception ex) when (ex is not OperationCanceledException) |
| | | 232 | | { |
| | 0 | 233 | | HttpContext.RequestServices.GetService<ILogger<OrderHistoryController>>() |
| | 0 | 234 | | ?.LogWarning(ex, "Не удалось собрать проблемы заказа {OrderId} для страницы истории", order.Id); |
| | 0 | 235 | | return []; |
| | | 236 | | } |
| | 0 | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <summary> |
| | | 240 | | /// Обогащает строки общей ленты orders_history цветом, поставщиком и стадией. |
| | | 241 | | /// Связь OrderHistoryId исключает эвристику по времени и повторное отображение перехода. |
| | | 242 | | /// </summary> |
| | | 243 | | private async Task<Dictionary<int, OrderSupplierStatusTimelineViewModel>> LoadSupplierStatusTimelineAsync( |
| | | 244 | | int orderId, |
| | | 245 | | CancellationToken cancellationToken) |
| | | 246 | | { |
| | 0 | 247 | | var transitions = await ( |
| | 0 | 248 | | from history in _context.OrderSupplierStateHistory.AsNoTracking() |
| | 0 | 249 | | join state in _context.OrderSupplierStates.AsNoTracking() |
| | 0 | 250 | | on history.OrderSupplierStateId equals state.Id |
| | 0 | 251 | | where history.OrderId == orderId && history.OrderHistoryId.HasValue |
| | 0 | 252 | | select new |
| | 0 | 253 | | { |
| | 0 | 254 | | TimelineHistoryId = history.OrderHistoryId!.Value, |
| | 0 | 255 | | state.ProviderKey, |
| | 0 | 256 | | history.FromSupplierStatusId, |
| | 0 | 257 | | history.ToSupplierStatusId, |
| | 0 | 258 | | history.FromStage, |
| | 0 | 259 | | history.ToStage, |
| | 0 | 260 | | history.Source, |
| | 0 | 261 | | history.Comment |
| | 0 | 262 | | }) |
| | 0 | 263 | | .ToListAsync(cancellationToken); |
| | | 264 | | |
| | 0 | 265 | | if (transitions.Count == 0) |
| | | 266 | | { |
| | 0 | 267 | | return new Dictionary<int, OrderSupplierStatusTimelineViewModel>(); |
| | | 268 | | } |
| | | 269 | | |
| | 0 | 270 | | var statusIds = transitions |
| | | 271 | | .SelectMany(item => new[] { item.FromSupplierStatusId, item.ToSupplierStatusId }) |
| | 0 | 272 | | .OfType<int>() |
| | 0 | 273 | | .Distinct() |
| | 0 | 274 | | .ToList(); |
| | | 275 | | |
| | 0 | 276 | | var statuses = await _context.SupplierStatuses |
| | 0 | 277 | | .AsNoTracking() |
| | 0 | 278 | | .Include(status => status.StatusColor) |
| | 0 | 279 | | .Where(status => statusIds.Contains(status.Id)) |
| | | 280 | | .ToDictionaryAsync(status => status.Id, cancellationToken); |
| | | 281 | | |
| | 0 | 282 | | return transitions.ToDictionary( |
| | | 283 | | item => item.TimelineHistoryId, |
| | 0 | 284 | | item => |
| | 0 | 285 | | { |
| | 0 | 286 | | statuses.TryGetValue(item.FromSupplierStatusId ?? 0, out var fromStatus); |
| | 0 | 287 | | statuses.TryGetValue(item.ToSupplierStatusId ?? 0, out var toStatus); |
| | 0 | 288 | | |
| | 0 | 289 | | return new OrderSupplierStatusTimelineViewModel |
| | 0 | 290 | | { |
| | 0 | 291 | | ProviderKey = item.ProviderKey, |
| | 0 | 292 | | FromStatusName = fromStatus?.Name, |
| | 0 | 293 | | FromStatusColor = fromStatus?.GetStatusColor(), |
| | 0 | 294 | | ToStatusName = toStatus?.Name ?? "Статус не указан", |
| | 0 | 295 | | ToStatusColor = toStatus?.GetStatusColor(), |
| | 0 | 296 | | FromStage = item.FromStage, |
| | 0 | 297 | | ToStage = item.ToStage, |
| | 0 | 298 | | Source = item.Source, |
| | 0 | 299 | | Comment = item.Comment |
| | 0 | 300 | | }; |
| | 0 | 301 | | }); |
| | 0 | 302 | | } |
| | | 303 | | |
| | | 304 | | private static OrderCalculationSnapshotHistoryViewModel MapCalculationSnapshot(OrderCalculationSnapshot snapshot) |
| | | 305 | | { |
| | 0 | 306 | | using var document = JsonDocument.Parse(snapshot.PayloadJson); |
| | 0 | 307 | | var root = document.RootElement; |
| | 0 | 308 | | static decimal Number(JsonElement root, string name) => root.TryGetProperty(name, out var value) && value.TryGet |
| | 0 | 309 | | static decimal? NullableNumber(JsonElement root, string name) => root.TryGetProperty(name, out var value) && val |
| | 0 | 310 | | return new OrderCalculationSnapshotHistoryViewModel |
| | 0 | 311 | | { |
| | 0 | 312 | | Id = snapshot.Id, |
| | 0 | 313 | | CapturedAt = snapshot.CapturedAt, |
| | 0 | 314 | | Source = snapshot.Source, |
| | 0 | 315 | | ShipmentAmount = Number(root, "shipmentAmount"), |
| | 0 | 316 | | CostPrice = Number(root, "costPrice"), |
| | 0 | 317 | | MinProfit = Number(root, "minProfit"), |
| | 0 | 318 | | MaxProfit = Number(root, "maxProfit"), |
| | 0 | 319 | | MinMarkup = NullableNumber(root, "minMarkup"), |
| | 0 | 320 | | MaxMarkup = NullableNumber(root, "maxMarkup") |
| | 0 | 321 | | }; |
| | 0 | 322 | | } |
| | | 323 | | |
| | | 324 | | [HttpGet] |
| | | 325 | | [PageAuthorize("Studio2.OrderHistory.GetOrderHistory")] |
| | | 326 | | public async Task<IActionResult> GetCalculationSnapshot(int orderId, long snapshotId, CancellationToken cancellation |
| | | 327 | | { |
| | 0 | 328 | | var order = await GetAccessibleOrderAsync(orderId, cancellationToken); |
| | 0 | 329 | | if (order == null) return NotFound(); |
| | | 330 | | |
| | 0 | 331 | | var snapshot = await _context.OrderCalculationSnapshots.AsNoTracking() |
| | 0 | 332 | | .FirstOrDefaultAsync(x => x.Id == snapshotId && x.OrderId == orderId, cancellationToken); |
| | 0 | 333 | | if (snapshot == null) return NotFound(); |
| | | 334 | | |
| | 0 | 335 | | return Content(snapshot.PayloadJson, "application/json"); |
| | 0 | 336 | | } |
| | | 337 | | |
| | | 338 | | [HttpGet] |
| | | 339 | | [PageAuthorize("Studio2.OrderHistory.GetOrderHistory")] |
| | | 340 | | public async Task<IActionResult> GetSupplierQuotationHistorySummary(int orderId, CancellationToken cancellationToken |
| | | 341 | | { |
| | 0 | 342 | | var order = await GetAccessibleOrderAsync(orderId, cancellationToken); |
| | 0 | 343 | | if (order?.ProductInfoId is not int productId) |
| | 0 | 344 | | return Ok(new { requests = 0, offers = 0, historyUrl = string.Empty }); |
| | | 345 | | |
| | 0 | 346 | | var summary = await _context.SupplierQuotationRequests.AsNoTracking() |
| | 0 | 347 | | .Where(x => x.ProductId == productId) |
| | 0 | 348 | | .GroupBy(_ => 1) |
| | 0 | 349 | | .Select(g => new { Requests = g.Count(), Offers = g.Sum(x => x.OffersCount) }) |
| | 0 | 350 | | .SingleOrDefaultAsync(cancellationToken); |
| | 0 | 351 | | return Ok(new |
| | 0 | 352 | | { |
| | 0 | 353 | | requests = summary?.Requests ?? 0, |
| | 0 | 354 | | offers = summary?.Offers ?? 0, |
| | 0 | 355 | | historyUrl = Url.Action(nameof(GetOrderHistory), new { area = "Studio2", orderId }) + "#tab-quotations" |
| | 0 | 356 | | }); |
| | 0 | 357 | | } |
| | | 358 | | |
| | | 359 | | private async Task<List<Transaction>> LoadTransactionsInScopeAsync(List<int> transactionIds) |
| | | 360 | | { |
| | 0 | 361 | | await using var scope = _scopeFactory.CreateAsyncScope(); |
| | 0 | 362 | | var svc = scope.ServiceProvider.GetRequiredService<TransactionDataServices>(); |
| | 0 | 363 | | return await svc.GetTransactionsByIdsAsync(transactionIds).ConfigureAwait(false) ?? new List<Transaction>(); |
| | 0 | 364 | | } |
| | | 365 | | |
| | | 366 | | private async Task<List<OrderShipmentTotalsHistoryRowViewModel>> LoadShipmentTotalsHistoryInScopeAsync(int orderId) |
| | | 367 | | { |
| | | 368 | | try |
| | | 369 | | { |
| | 0 | 370 | | await using var scope = _scopeFactory.CreateAsyncScope(); |
| | 0 | 371 | | var svc = scope.ServiceProvider.GetRequiredService<IOrderShipmentTotalsDataService>(); |
| | 0 | 372 | | var entities = await svc.GetHistoryByOrderIdAsync(orderId).ConfigureAwait(false); |
| | 0 | 373 | | return entities |
| | | 374 | | .Select(e => new OrderShipmentTotalsHistoryRowViewModel |
| | | 375 | | { |
| | | 376 | | UpdatedAt = e.UpdatedAt, |
| | | 377 | | ListAmount = e.ListAmount, |
| | | 378 | | AccrualsForSale = e.AccrualsForSale, |
| | | 379 | | SaleCommission = e.SaleCommission, |
| | | 380 | | ProcessingAndDelivery = e.ProcessingAndDelivery, |
| | | 381 | | RefundsAndCancellations = e.RefundsAndCancellations |
| | | 382 | | }) |
| | 0 | 383 | | .ToList(); |
| | 0 | 384 | | } |
| | 0 | 385 | | catch |
| | | 386 | | { |
| | 0 | 387 | | return new List<OrderShipmentTotalsHistoryRowViewModel>(); |
| | | 388 | | } |
| | 0 | 389 | | } |
| | | 390 | | |
| | | 391 | | private async Task<List<OrderHistoryOneCPostingViewModel>> LoadOneCPostingsInScopeAsync(int orderId) |
| | | 392 | | { |
| | | 393 | | try |
| | | 394 | | { |
| | 0 | 395 | | await using var scope = _scopeFactory.CreateAsyncScope(); |
| | 0 | 396 | | var svc = scope.ServiceProvider.GetRequiredService<IOrderHistoryOneCPostingService>(); |
| | 0 | 397 | | var postings = await svc.GetByOrderIdAsync(orderId).ConfigureAwait(false); |
| | 0 | 398 | | return postings |
| | | 399 | | .Select(p => new OrderHistoryOneCPostingViewModel |
| | | 400 | | { |
| | | 401 | | Id = p.Id, |
| | | 402 | | OrderId = p.OrderId, |
| | | 403 | | TransactionId = p.TransactionId, |
| | | 404 | | OperationKind = p.OperationKind, |
| | | 405 | | Success = p.Success, |
| | | 406 | | PostedAt = p.PostedAt, |
| | | 407 | | ChangedBy = p.ChangedBy, |
| | | 408 | | HistoryBatchKey = p.HistoryBatchKey, |
| | | 409 | | LinkedHistoryIds = p.HistoryLinks?.Select(l => l.OrderHistoryId).ToList() ?? new List<int>(), |
| | | 410 | | OrganizationName = p.OrganizationName, |
| | | 411 | | OrganizationInn = p.OrganizationInn, |
| | | 412 | | SenderName = p.SenderName, |
| | | 413 | | SenderInn = p.SenderInn, |
| | | 414 | | WarehouseSender = p.WarehouseSender, |
| | | 415 | | WarehouseRecipient = p.WarehouseRecipient, |
| | | 416 | | OrdersCount = p.OrdersCount, |
| | | 417 | | ProductsCount = p.ProductsCount, |
| | | 418 | | ArticlesSummary = p.ArticlesSummary, |
| | | 419 | | DocumentsCount = p.DocumentsCount, |
| | | 420 | | DocumentNumbers = p.DocumentNumbers, |
| | | 421 | | DocumentGuids = p.DocumentGuids, |
| | | 422 | | IsPosted = p.IsPosted, |
| | | 423 | | ErrorSummary = p.ErrorSummary, |
| | | 424 | | CreatedNomenclature = GetCreatedNomenclature(p.DetailsJson) |
| | | 425 | | }) |
| | 0 | 426 | | .ToList(); |
| | 0 | 427 | | } |
| | 0 | 428 | | catch |
| | | 429 | | { |
| | 0 | 430 | | return new List<OrderHistoryOneCPostingViewModel>(); |
| | | 431 | | } |
| | 0 | 432 | | } |
| | | 433 | | |
| | | 434 | | private async Task<List<OrderHistoryHandoverItemViewModel>> LoadHandoverItemsInScopeAsync(int orderId) |
| | | 435 | | { |
| | | 436 | | try |
| | | 437 | | { |
| | 0 | 438 | | await using var scope = _scopeFactory.CreateAsyncScope(); |
| | 0 | 439 | | var repository = scope.ServiceProvider.GetRequiredService<OzonHandoverRepository>(); |
| | 0 | 440 | | var items = await repository.GetItemsByOrderIdsAsync(new[] { orderId }).ConfigureAwait(false); |
| | 0 | 441 | | return items |
| | | 442 | | .OrderByDescending(i => i.MarkedAt ?? i.Act?.ActDate ?? DateTime.MinValue) |
| | | 443 | | .Select(i => new OrderHistoryHandoverItemViewModel |
| | | 444 | | { |
| | | 445 | | GroupName = i.Act?.GroupName, |
| | | 446 | | ActNo = i.Act?.ActNo, |
| | | 447 | | ActDate = i.Act?.ActDate ?? default, |
| | | 448 | | ActType = i.Act?.ActType, |
| | | 449 | | Pvz = i.Act?.Pvz, |
| | | 450 | | ActStatus = i.Act?.Status, |
| | | 451 | | ProductName = i.ProductName, |
| | | 452 | | Barcode = i.Barcode, |
| | | 453 | | Value = i.Value, |
| | | 454 | | ValueApi = i.ValueApi, |
| | | 455 | | WeightG = i.WeightG, |
| | | 456 | | Status = i.Status, |
| | | 457 | | Defect = i.Defect, |
| | | 458 | | Missort = i.Missort, |
| | | 459 | | Comment = i.Comment, |
| | | 460 | | MarkedAt = i.MarkedAt, |
| | | 461 | | Sku = i.Sku, |
| | | 462 | | OfferId = i.OfferId, |
| | | 463 | | ReturnId = i.ReturnId, |
| | | 464 | | OzonStatus = i.OzonStatus, |
| | | 465 | | OzonStatusName = i.OzonStatusName, |
| | | 466 | | ReturnType = i.ReturnType ?? i.Act?.ReturnType, |
| | | 467 | | BoxBarcode = i.BoxBarcode ?? i.Act?.BoxBarcode, |
| | | 468 | | Reason = i.Reason, |
| | | 469 | | ReasonIsDefect = i.ReasonIsDefect, |
| | | 470 | | ClientComment = i.ClientComment, |
| | | 471 | | RejectionComment = i.RejectionComment, |
| | | 472 | | RejectionReason = i.RejectionReason, |
| | | 473 | | RuPostTracking = i.RuPostTracking, |
| | | 474 | | ReturnNumber = i.ReturnNumber, |
| | | 475 | | OrderNumber = i.OrderNumber, |
| | | 476 | | ClientReturnMethod = i.ClientReturnMethod, |
| | | 477 | | WarehouseId = i.WarehouseId, |
| | | 478 | | PhotosError = i.PhotosError, |
| | | 479 | | Photos = i.Photos.OrderBy(p => p.Sequence).Select(p => new OrderHistoryHandoverPhotoViewModel |
| | | 480 | | { |
| | | 481 | | Id = p.Id, |
| | | 482 | | Sequence = p.Sequence |
| | | 483 | | }).ToList() |
| | | 484 | | }) |
| | 0 | 485 | | .ToList(); |
| | 0 | 486 | | } |
| | 0 | 487 | | catch |
| | | 488 | | { |
| | 0 | 489 | | return new List<OrderHistoryHandoverItemViewModel>(); |
| | | 490 | | } |
| | 0 | 491 | | } |
| | | 492 | | |
| | | 493 | | private async Task<List<OrderHistoryLabelPrintViewModel>> LoadLabelPrintsInScopeAsync(int orderId) |
| | | 494 | | { |
| | 0 | 495 | | await using var scope = _scopeFactory.CreateAsyncScope(); |
| | 0 | 496 | | var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); |
| | 0 | 497 | | var entries = await context.LabelPrintLogs.AsNoTracking() |
| | 0 | 498 | | .Where(x => x.OrderId == orderId) |
| | 0 | 499 | | .OrderByDescending(x => x.OccurredAtUtc) |
| | 0 | 500 | | .Select(x => new OrderHistoryLabelPrintViewModel |
| | 0 | 501 | | { |
| | 0 | 502 | | Id = x.Id, |
| | 0 | 503 | | FileName = x.FileName, |
| | 0 | 504 | | OccurredAtUtc = x.OccurredAtUtc, |
| | 0 | 505 | | ActorName = x.ActorName, |
| | 0 | 506 | | Source = x.Source |
| | 0 | 507 | | }) |
| | 0 | 508 | | .ToListAsync() |
| | 0 | 509 | | .ConfigureAwait(false); |
| | | 510 | | |
| | | 511 | | var result = entries.Select(x => new OrderHistoryLabelPrintViewModel |
| | | 512 | | { |
| | | 513 | | Id = x.Id, |
| | | 514 | | FileName = x.FileName, |
| | | 515 | | OccurredAtUtc = DateTime.SpecifyKind(x.OccurredAtUtc, DateTimeKind.Utc), |
| | | 516 | | ActorName = x.ActorName, |
| | | 517 | | Source = x.Source |
| | | 518 | | }).ToList(); |
| | | 519 | | |
| | | 520 | | // Старые PDF существовали до появления журнала. Добавляем их в ленту по дате изменения |
| | | 521 | | // файла, не выдавая эту дату за подтверждённую печать и не выдумывая исполнителя. |
| | 0 | 522 | | var catalog = scope.ServiceProvider.GetRequiredService<ILabelCatalogService>(); |
| | 0 | 523 | | var snapshot = await catalog.GetSnapshotAsync(cancellationToken: HttpContext.RequestAborted).ConfigureAwait(fals |
| | 0 | 524 | | result.AddRange(snapshot.Rows |
| | 0 | 525 | | .Where(x => x.UsesFileDate && x.RelatedOrderIds.Contains(orderId)) |
| | | 526 | | .Select(x => new OrderHistoryLabelPrintViewModel |
| | | 527 | | { |
| | | 528 | | Id = -x.Id, |
| | | 529 | | FileName = x.FileName, |
| | | 530 | | OccurredAtUtc = x.PrintedAtUtc.UtcDateTime, |
| | | 531 | | ActorName = "—", |
| | | 532 | | Source = LabelPrintSource.Studio2, |
| | | 533 | | UsesFileDate = true |
| | | 534 | | })); |
| | | 535 | | |
| | | 536 | | return result.OrderByDescending(x => x.OccurredAtUtc).ThenByDescending(x => x.Id).ToList(); |
| | 0 | 537 | | } |
| | | 538 | | |
| | | 539 | | private static string? GetCreatedNomenclature(string? detailsJson) |
| | | 540 | | { |
| | 0 | 541 | | if (string.IsNullOrWhiteSpace(detailsJson)) |
| | 0 | 542 | | return null; |
| | | 543 | | |
| | | 544 | | try |
| | | 545 | | { |
| | 0 | 546 | | var details = JsonConvert.DeserializeAnonymousType(detailsJson, |
| | 0 | 547 | | new { responses = Array.Empty<OneCResponse>() }); |
| | 0 | 548 | | return details?.responses |
| | 0 | 549 | | .Select(r => r.CreatedNomenclature) |
| | 0 | 550 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 0 | 551 | | .Distinct() |
| | 0 | 552 | | .DefaultIfEmpty() |
| | 0 | 553 | | .Aggregate((a, b) => string.IsNullOrWhiteSpace(a) ? b : $"{a}; {b}"); |
| | | 554 | | } |
| | 0 | 555 | | catch (Newtonsoft.Json.JsonException) |
| | | 556 | | { |
| | 0 | 557 | | return null; |
| | | 558 | | } |
| | 0 | 559 | | } |
| | | 560 | | |
| | | 561 | | /// <summary> |
| | | 562 | | /// Подгружает начисления Ozon для указанного заказа (по номеру отправления) и возвращает |
| | | 563 | | /// подробные операции для отображения в модальном окне на странице заказов. |
| | | 564 | | /// </summary> |
| | | 565 | | [HttpGet] |
| | | 566 | | public async Task<IActionResult> GetShipmentTotals(int orderId) |
| | | 567 | | { |
| | 0 | 568 | | var cacheKey = $"{ShipmentTotalsCacheKeyPrefix}{orderId}"; |
| | 0 | 569 | | if (_memoryCache.TryGetValue(cacheKey, out object? cached) && cached != null) |
| | | 570 | | { |
| | | 571 | | // В случае кеша данные уже были сформированы ранее, но требование — сохранять при каждом запросе. |
| | | 572 | | try |
| | | 573 | | { |
| | 0 | 574 | | EnqueueSaveShipmentTotalsToDbFromCachedPayload(orderId, cached); |
| | 0 | 575 | | } |
| | 0 | 576 | | catch |
| | | 577 | | { |
| | | 578 | | // Без ошибок на UI. |
| | 0 | 579 | | } |
| | | 580 | | |
| | 0 | 581 | | return Ok(cached); |
| | | 582 | | } |
| | | 583 | | |
| | 0 | 584 | | var order = await _ordersDataServices.GetAsyncNoTracking(orderId).ConfigureAwait(false); |
| | 0 | 585 | | if (order == null) |
| | 0 | 586 | | return NotFound($"Заказ {orderId} не найден."); |
| | | 587 | | |
| | 0 | 588 | | var clientWithDecrypted = await ResolveOzonClientAsync(order).ConfigureAwait(false); |
| | 0 | 589 | | if (clientWithDecrypted == null) |
| | | 590 | | { |
| | 0 | 591 | | var emptyPayload = new |
| | 0 | 592 | | { |
| | 0 | 593 | | orderId, |
| | 0 | 594 | | shipmentNumber = order?.ShipmentNumber, |
| | 0 | 595 | | clientName = order?.OzonClient?.Name, |
| | 0 | 596 | | listAmount = 0d, |
| | 0 | 597 | | operations = new List<object>(), |
| | 0 | 598 | | totals = (object?)null |
| | 0 | 599 | | }; |
| | 0 | 600 | | return Ok(emptyPayload); |
| | | 601 | | } |
| | | 602 | | |
| | | 603 | | // Seller API требует последовательных вызовов новых методов finance/accrual. |
| | 0 | 604 | | var financeSummary = await LoadFinanceAccrualSummaryInScopeAsync(order, clientWithDecrypted).ConfigureAwait(fals |
| | 0 | 605 | | var operations = financeSummary.Operations; |
| | 0 | 606 | | var financeTotals = financeSummary.Totals; |
| | | 607 | | |
| | | 608 | | double listAmount = operations?.Sum(o => o.Amount) ?? 0d; |
| | 0 | 609 | | var operationsDto = BuildOperationsDto(operations ?? new List<FinanceTransactionOperation>()); |
| | 0 | 610 | | var totalsDto = BuildTotalsDto(financeTotals); |
| | | 611 | | |
| | 0 | 612 | | var payload = new |
| | 0 | 613 | | { |
| | 0 | 614 | | orderId, |
| | 0 | 615 | | shipmentNumber = order?.ShipmentNumber, |
| | 0 | 616 | | clientName = order?.OzonClient?.Name, |
| | 0 | 617 | | listAmount, |
| | 0 | 618 | | operations = operationsDto, |
| | 0 | 619 | | totals = totalsDto |
| | 0 | 620 | | }; |
| | | 621 | | |
| | 0 | 622 | | _memoryCache.Set(cacheKey, payload, new MemoryCacheEntryOptions |
| | 0 | 623 | | { |
| | 0 | 624 | | AbsoluteExpirationRelativeToNow = ShipmentTotalsCacheAbsoluteExpiration, |
| | 0 | 625 | | SlidingExpiration = ShipmentTotalsCacheSlidingExpiration |
| | 0 | 626 | | }); |
| | | 627 | | |
| | | 628 | | // Upsert в БД (операции + totals) в фоне. |
| | | 629 | | try |
| | | 630 | | { |
| | 0 | 631 | | EnqueueSaveShipmentTotalsToDb( |
| | 0 | 632 | | orderId, |
| | 0 | 633 | | order?.ShipmentNumber, |
| | 0 | 634 | | listAmount, |
| | 0 | 635 | | operationsDto, |
| | 0 | 636 | | financeTotals, |
| | 0 | 637 | | operations?.Count ?? 0); |
| | 0 | 638 | | } |
| | 0 | 639 | | catch |
| | | 640 | | { |
| | | 641 | | // Без ошибок на UI. |
| | 0 | 642 | | } |
| | | 643 | | |
| | 0 | 644 | | return Ok(payload); |
| | 0 | 645 | | } |
| | | 646 | | |
| | | 647 | | /// <summary> |
| | | 648 | | /// Batch для preload на странице заказов: только закэшированные listAmount (без вызовов Ozon API). |
| | | 649 | | /// </summary> |
| | | 650 | | [HttpGet] |
| | | 651 | | public IActionResult GetShipmentTotalsBatch([FromQuery] string orderIds) |
| | | 652 | | { |
| | 0 | 653 | | if (string.IsNullOrWhiteSpace(orderIds)) |
| | | 654 | | { |
| | 0 | 655 | | return Ok(new { results = Array.Empty<object>() }); |
| | | 656 | | } |
| | | 657 | | |
| | 0 | 658 | | var ids = orderIds |
| | 0 | 659 | | .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) |
| | 0 | 660 | | .Select(s => int.TryParse(s, out var id) ? id : 0) |
| | 0 | 661 | | .Where(id => id > 0) |
| | 0 | 662 | | .Distinct() |
| | 0 | 663 | | .Take(50) |
| | 0 | 664 | | .ToList(); |
| | | 665 | | |
| | 0 | 666 | | var results = new List<object>(); |
| | 0 | 667 | | foreach (var id in ids) |
| | | 668 | | { |
| | 0 | 669 | | var cacheKey = $"{ShipmentTotalsCacheKeyPrefix}{id}"; |
| | 0 | 670 | | if (!_memoryCache.TryGetValue(cacheKey, out var cached) || cached is null) |
| | | 671 | | { |
| | | 672 | | continue; |
| | | 673 | | } |
| | | 674 | | |
| | | 675 | | try |
| | | 676 | | { |
| | 0 | 677 | | var jo = Newtonsoft.Json.Linq.JObject.FromObject(cached); |
| | 0 | 678 | | results.Add(new |
| | 0 | 679 | | { |
| | 0 | 680 | | orderId = id, |
| | 0 | 681 | | listAmount = jo["listAmount"]?.ToObject<double?>() ?? 0d |
| | 0 | 682 | | }); |
| | 0 | 683 | | } |
| | 0 | 684 | | catch |
| | | 685 | | { |
| | | 686 | | // Пропускаем битые записи кэша. |
| | 0 | 687 | | } |
| | | 688 | | } |
| | | 689 | | |
| | 0 | 690 | | return Ok(new { results }); |
| | | 691 | | } |
| | | 692 | | |
| | | 693 | | private static string? FormatDate(string? s) |
| | | 694 | | { |
| | 0 | 695 | | if (string.IsNullOrWhiteSpace(s)) |
| | 0 | 696 | | return null; |
| | | 697 | | |
| | 0 | 698 | | return DateTime.TryParse( |
| | 0 | 699 | | s, |
| | 0 | 700 | | null, |
| | 0 | 701 | | System.Globalization.DateTimeStyles.RoundtripKind, |
| | 0 | 702 | | out var d) |
| | 0 | 703 | | ? d.ToString("dd.MM.yyyy") |
| | 0 | 704 | | : s; |
| | | 705 | | } |
| | | 706 | | |
| | | 707 | | private static string? FormatDateTime(string? s) |
| | | 708 | | { |
| | 0 | 709 | | if (string.IsNullOrWhiteSpace(s)) |
| | 0 | 710 | | return null; |
| | | 711 | | |
| | 0 | 712 | | return DateTime.TryParse( |
| | 0 | 713 | | s, |
| | 0 | 714 | | null, |
| | 0 | 715 | | System.Globalization.DateTimeStyles.RoundtripKind, |
| | 0 | 716 | | out var d) |
| | 0 | 717 | | ? d.ToString("dd.MM.yyyy HH:mm") |
| | 0 | 718 | | : s; |
| | | 719 | | } |
| | | 720 | | |
| | | 721 | | private static object BuildOperationsDto(List<FinanceTransactionOperation> operations) |
| | | 722 | | { |
| | 0 | 723 | | return (operations ?? new List<FinanceTransactionOperation>()) |
| | 0 | 724 | | .Select(op => new |
| | 0 | 725 | | { |
| | 0 | 726 | | operationId = op.OperationId, |
| | 0 | 727 | | operationType = op.OperationType, |
| | 0 | 728 | | operationTypeName = OzonStatus.GetFinanceOperationType(op.OperationType ?? string.Empty), |
| | 0 | 729 | | operationDate = FormatDate(op.OperationDate), |
| | 0 | 730 | | |
| | 0 | 731 | | // В истории поле "Категория" берётся из op.Type -> OzonStatus.GetFinanceTransactionType(...) |
| | 0 | 732 | | type = op.Type, |
| | 0 | 733 | | transactionTypeName = OzonStatus.GetFinanceTransactionType(op.Type ?? string.Empty), |
| | 0 | 734 | | |
| | 0 | 735 | | amount = op.Amount, |
| | 0 | 736 | | accrualsForSale = op.AccrualsForSale, |
| | 0 | 737 | | saleCommission = op.SaleCommission, |
| | 0 | 738 | | deliveryCharge = op.DeliveryCharge, |
| | 0 | 739 | | returnDeliveryCharge = op.ReturnDeliveryCharge, |
| | 0 | 740 | | |
| | 0 | 741 | | posting = op.Posting == null |
| | 0 | 742 | | ? null |
| | 0 | 743 | | : new |
| | 0 | 744 | | { |
| | 0 | 745 | | deliverySchema = op.Posting.DeliverySchema, |
| | 0 | 746 | | postingNumber = op.Posting.PostingNumber, |
| | 0 | 747 | | warehouseId = op.Posting.WarehouseId, |
| | 0 | 748 | | orderDate = FormatDateTime(op.Posting.OrderDate) |
| | 0 | 749 | | }, |
| | 0 | 750 | | |
| | 0 | 751 | | items = (op.Items ?? new List<FinanceTransactionItem>()) |
| | 0 | 752 | | .Select(i => new { name = i.Name, sku = i.Sku }) |
| | 0 | 753 | | .ToList(), |
| | 0 | 754 | | |
| | 0 | 755 | | // В истории названия услуг переводятся через OzonStatus.GetFinanceServiceName(...) |
| | 0 | 756 | | services = (op.Services ?? new List<FinanceTransactionService>()) |
| | 0 | 757 | | .Select(s => new |
| | 0 | 758 | | { |
| | 0 | 759 | | name = OzonStatus.GetFinanceServiceName(s.Name), |
| | 0 | 760 | | price = s.Price |
| | 0 | 761 | | }) |
| | 0 | 762 | | .ToList() |
| | 0 | 763 | | }) |
| | 0 | 764 | | .ToList(); |
| | | 765 | | } |
| | | 766 | | |
| | | 767 | | private static object? BuildTotalsDto(FinanceTransactionTotalsResult? financeTotals) |
| | | 768 | | { |
| | 0 | 769 | | return financeTotals == null |
| | 0 | 770 | | ? null |
| | 0 | 771 | | : new |
| | 0 | 772 | | { |
| | 0 | 773 | | accrualsForSale = financeTotals.AccrualsForSale, |
| | 0 | 774 | | saleCommission = financeTotals.SaleCommission, |
| | 0 | 775 | | processingAndDelivery = financeTotals.ProcessingAndDelivery, |
| | 0 | 776 | | refundsAndCancellations = financeTotals.RefundsAndCancellations, |
| | 0 | 777 | | servicesAmount = financeTotals.ServicesAmount, |
| | 0 | 778 | | compensationAmount = financeTotals.CompensationAmount, |
| | 0 | 779 | | moneyTransfer = financeTotals.MoneyTransfer, |
| | 0 | 780 | | othersAmount = financeTotals.OthersAmount |
| | 0 | 781 | | }; |
| | | 782 | | } |
| | | 783 | | |
| | | 784 | | private void EnqueueSaveShipmentTotalsToDb( |
| | | 785 | | int orderId, |
| | | 786 | | string? shipmentNumber, |
| | | 787 | | double listAmount, |
| | | 788 | | object operationsDto, |
| | | 789 | | FinanceTransactionTotalsResult? financeTotals, |
| | | 790 | | int operationsCount) |
| | | 791 | | { |
| | | 792 | | // Не создаём фоновые задачи для пустых/нулевых результатов. |
| | 0 | 793 | | if (operationsCount <= 0 || Math.Abs(listAmount) < 0.000001) |
| | 0 | 794 | | return; |
| | | 795 | | |
| | 0 | 796 | | _ = Task.Run(async () => |
| | 0 | 797 | | { |
| | 0 | 798 | | try |
| | 0 | 799 | | { |
| | 0 | 800 | | using var scope = _scopeFactory.CreateScope(); |
| | 0 | 801 | | var svc = scope.ServiceProvider.GetRequiredService<IOrderShipmentTotalsDataService>(); |
| | 0 | 802 | | |
| | 0 | 803 | | await SaveShipmentTotalsToDbAsync( |
| | 0 | 804 | | svc, |
| | 0 | 805 | | orderId, |
| | 0 | 806 | | shipmentNumber, |
| | 0 | 807 | | listAmount, |
| | 0 | 808 | | operationsDto, |
| | 0 | 809 | | financeTotals, |
| | 0 | 810 | | operationsCount) |
| | 0 | 811 | | .ConfigureAwait(false); |
| | 0 | 812 | | } |
| | 0 | 813 | | catch |
| | 0 | 814 | | { |
| | 0 | 815 | | // Не ломаем UI из-за фоновых сохранений. |
| | 0 | 816 | | } |
| | 0 | 817 | | }); |
| | 0 | 818 | | } |
| | | 819 | | |
| | | 820 | | private void EnqueueSaveShipmentTotalsToDbFromCachedPayload( |
| | | 821 | | int orderId, |
| | | 822 | | object cachedPayload) |
| | | 823 | | { |
| | 0 | 824 | | _ = Task.Run(async () => |
| | 0 | 825 | | { |
| | 0 | 826 | | try |
| | 0 | 827 | | { |
| | 0 | 828 | | using var scope = _scopeFactory.CreateScope(); |
| | 0 | 829 | | var svc = scope.ServiceProvider.GetRequiredService<IOrderShipmentTotalsDataService>(); |
| | 0 | 830 | | |
| | 0 | 831 | | await SaveShipmentTotalsToDbFromCachedPayloadAsync( |
| | 0 | 832 | | svc, |
| | 0 | 833 | | orderId, |
| | 0 | 834 | | cachedPayload) |
| | 0 | 835 | | .ConfigureAwait(false); |
| | 0 | 836 | | } |
| | 0 | 837 | | catch |
| | 0 | 838 | | { |
| | 0 | 839 | | // Не ломаем UI из-за фоновых сохранений. |
| | 0 | 840 | | } |
| | 0 | 841 | | }); |
| | 0 | 842 | | } |
| | | 843 | | |
| | | 844 | | private async Task SaveShipmentTotalsToDbAsync( |
| | | 845 | | IOrderShipmentTotalsDataService svc, |
| | | 846 | | int orderId, |
| | | 847 | | string? shipmentNumber, |
| | | 848 | | double listAmount, |
| | | 849 | | object operationsDto, |
| | | 850 | | FinanceTransactionTotalsResult? financeTotals, |
| | | 851 | | int operationsCount) |
| | | 852 | | { |
| | 0 | 853 | | var entity = new OrderShipmentTotals |
| | 0 | 854 | | { |
| | 0 | 855 | | OrderId = orderId, |
| | 0 | 856 | | ShipmentNumber = shipmentNumber, |
| | 0 | 857 | | ListAmount = listAmount, |
| | 0 | 858 | | |
| | 0 | 859 | | AccrualsForSale = financeTotals?.AccrualsForSale ?? 0d, |
| | 0 | 860 | | SaleCommission = financeTotals?.SaleCommission ?? 0d, |
| | 0 | 861 | | ProcessingAndDelivery = financeTotals?.ProcessingAndDelivery ?? 0d, |
| | 0 | 862 | | RefundsAndCancellations = financeTotals?.RefundsAndCancellations ?? 0d, |
| | 0 | 863 | | ServicesAmount = financeTotals?.ServicesAmount ?? 0d, |
| | 0 | 864 | | CompensationAmount = financeTotals?.CompensationAmount ?? 0d, |
| | 0 | 865 | | MoneyTransfer = financeTotals?.MoneyTransfer ?? 0d, |
| | 0 | 866 | | OthersAmount = financeTotals?.OthersAmount ?? 0d, |
| | 0 | 867 | | |
| | 0 | 868 | | OperationsCount = operationsCount, |
| | 0 | 869 | | OperationsJson = JsonConvert.SerializeObject(operationsDto) |
| | 0 | 870 | | }; |
| | | 871 | | |
| | 0 | 872 | | await svc.SetOrUpdateAsync(entity).ConfigureAwait(false); |
| | 0 | 873 | | } |
| | | 874 | | |
| | | 875 | | private async Task SaveShipmentTotalsToDbFromCachedPayloadAsync( |
| | | 876 | | IOrderShipmentTotalsDataService svc, |
| | | 877 | | int orderId, |
| | | 878 | | object cachedPayload) |
| | | 879 | | { |
| | 0 | 880 | | dynamic payload = cachedPayload; |
| | | 881 | | |
| | 0 | 882 | | var operationsDto = payload.operations; |
| | 0 | 883 | | int operationsCount = operationsDto?.Count ?? 0; |
| | | 884 | | |
| | 0 | 885 | | if (operationsCount <= 0 || Math.Abs((double)payload.listAmount) < 0.000001) |
| | 0 | 886 | | return; |
| | | 887 | | |
| | | 888 | | // totalsDto уже отсортирован/назван как в ответе GetShipmentTotals. |
| | 0 | 889 | | dynamic totals = payload.totals; |
| | | 890 | | |
| | | 891 | | static double SafeTotal(dynamic t, string propName) |
| | | 892 | | { |
| | 0 | 893 | | if (t == null) |
| | 0 | 894 | | return 0d; |
| | | 895 | | |
| | | 896 | | try |
| | | 897 | | { |
| | 0 | 898 | | var prop = ((object)t).GetType().GetProperty(propName); |
| | 0 | 899 | | if (prop == null) return 0d; |
| | 0 | 900 | | var v = prop.GetValue(t); |
| | 0 | 901 | | return v == null ? 0d : Convert.ToDouble(v); |
| | | 902 | | } |
| | 0 | 903 | | catch |
| | | 904 | | { |
| | 0 | 905 | | return 0d; |
| | | 906 | | } |
| | 0 | 907 | | } |
| | | 908 | | |
| | 0 | 909 | | var entity = new OrderShipmentTotals |
| | 0 | 910 | | { |
| | 0 | 911 | | OrderId = orderId, |
| | 0 | 912 | | ShipmentNumber = payload.shipmentNumber, |
| | 0 | 913 | | ListAmount = payload.listAmount, |
| | 0 | 914 | | |
| | 0 | 915 | | AccrualsForSale = SafeTotal(totals, "accrualsForSale"), |
| | 0 | 916 | | SaleCommission = SafeTotal(totals, "saleCommission"), |
| | 0 | 917 | | ProcessingAndDelivery = SafeTotal(totals, "processingAndDelivery"), |
| | 0 | 918 | | RefundsAndCancellations = SafeTotal(totals, "refundsAndCancellations"), |
| | 0 | 919 | | ServicesAmount = SafeTotal(totals, "servicesAmount"), |
| | 0 | 920 | | CompensationAmount = SafeTotal(totals, "compensationAmount"), |
| | 0 | 921 | | MoneyTransfer = SafeTotal(totals, "moneyTransfer"), |
| | 0 | 922 | | OthersAmount = SafeTotal(totals, "othersAmount"), |
| | 0 | 923 | | |
| | 0 | 924 | | OperationsCount = operationsCount, |
| | 0 | 925 | | OperationsJson = JsonConvert.SerializeObject(operationsDto) |
| | 0 | 926 | | }; |
| | | 927 | | |
| | 0 | 928 | | await svc.SetOrUpdateAsync(entity).ConfigureAwait(false); |
| | 0 | 929 | | } |
| | | 930 | | |
| | | 931 | | private async Task<OzonClient?> ResolveOzonClientAsync(Order? order) |
| | | 932 | | { |
| | 0 | 933 | | if (order?.OzonClientId == null || string.IsNullOrWhiteSpace(order.ShipmentNumber)) |
| | 0 | 934 | | return null; |
| | | 935 | | |
| | | 936 | | try |
| | | 937 | | { |
| | 0 | 938 | | var client = await _ozonClientServices.GetOzonClientAsync(order.OzonClientId.Value).ConfigureAwait(false); |
| | 0 | 939 | | if (client == null || string.IsNullOrWhiteSpace(client.DecryptClientId) || string.IsNullOrWhiteSpace(client. |
| | 0 | 940 | | return null; |
| | 0 | 941 | | return client; |
| | | 942 | | } |
| | 0 | 943 | | catch |
| | | 944 | | { |
| | 0 | 945 | | return null; |
| | | 946 | | } |
| | 0 | 947 | | } |
| | | 948 | | |
| | | 949 | | private async Task<FinanceAccrualSummary> LoadFinanceAccrualSummaryInScopeAsync(Order? order, OzonClient clientWithD |
| | | 950 | | { |
| | 0 | 951 | | await using var scope = _scopeFactory.CreateAsyncScope(); |
| | 0 | 952 | | var ozonApi = scope.ServiceProvider.GetRequiredService<OzonApiDataManager>(); |
| | 0 | 953 | | return await LoadFinanceAccrualSummaryAsync(order, clientWithDecrypted, ozonApi).ConfigureAwait(false); |
| | 0 | 954 | | } |
| | | 955 | | |
| | | 956 | | private async Task<FinanceAccrualSummary> LoadFinanceAccrualSummaryAsync( |
| | | 957 | | Order? order, |
| | | 958 | | OzonClient clientWithDecrypted, |
| | | 959 | | OzonApiDataManager? ozonApiDataManager = null) |
| | | 960 | | { |
| | 0 | 961 | | var ozonApi = ozonApiDataManager ?? _ozonApiDataManager; |
| | 0 | 962 | | var empty = new FinanceAccrualSummary(); |
| | 0 | 963 | | if (order == null || string.IsNullOrWhiteSpace(order.ShipmentNumber)) |
| | 0 | 964 | | return empty; |
| | | 965 | | |
| | | 966 | | try |
| | | 967 | | { |
| | 0 | 968 | | ozonApi.SetClient(clientWithDecrypted.DecryptClientId!, clientWithDecrypted.DecryptApiKey!); |
| | 0 | 969 | | var accruals = await ozonApi.GetFinanceAccrualPostingsAsync(new FinanceAccrualPostingsRequest |
| | 0 | 970 | | { |
| | 0 | 971 | | PostingNumbers = new List<string> { order.ShipmentNumber } |
| | 0 | 972 | | }).ConfigureAwait(false); |
| | 0 | 973 | | var types = await ozonApi.GetFinanceAccrualTypesAsync().ConfigureAwait(false); |
| | 0 | 974 | | return FinanceAccrualSummaryBuilder.Build(accruals, types); |
| | | 975 | | } |
| | 0 | 976 | | catch |
| | | 977 | | { |
| | | 978 | | // Начисления по API могут быть недоступны — не ломаем страницу истории. |
| | 0 | 979 | | return empty; |
| | | 980 | | } |
| | 0 | 981 | | } |
| | | 982 | | |
| | | 983 | | /// <summary> |
| | | 984 | | /// Собирает ID транзакций: текущая транзакция заказа + из истории изменений поля TransactionId. |
| | | 985 | | /// </summary> |
| | | 986 | | private static List<int> CollectTransactionIds(Order? order, List<OrderHistory> histories) |
| | | 987 | | { |
| | 0 | 988 | | var ids = new HashSet<int>(); |
| | | 989 | | |
| | 0 | 990 | | if (order?.TransactionId.HasValue == true && order.TransactionId.Value > 0) |
| | 0 | 991 | | ids.Add(order.TransactionId.Value); |
| | | 992 | | |
| | 0 | 993 | | foreach (var h in histories) |
| | | 994 | | { |
| | 0 | 995 | | var isTransactionColumn = string.Equals(h.ColumnName, "TransactionId", StringComparison.OrdinalIgnoreCase) | |
| | 0 | 996 | | (h.ColumnDisplayName != null && h.ColumnDisplayName.IndexOf("Транзакция", StringCo |
| | 0 | 997 | | if (!isTransactionColumn) continue; |
| | | 998 | | |
| | 0 | 999 | | if (int.TryParse(h.NewValue, out var newId) && newId > 0) ids.Add(newId); |
| | 0 | 1000 | | if (int.TryParse(h.OldValue, out var oldId) && oldId > 0) ids.Add(oldId); |
| | | 1001 | | } |
| | | 1002 | | |
| | 0 | 1003 | | return ids.ToList(); |
| | | 1004 | | } |
| | | 1005 | | |
| | | 1006 | | [HttpGet] |
| | | 1007 | | [PageAuthorize("Studio2.OrderHistory.ExportBitrixSyncHistoryExcel")] |
| | | 1008 | | public async Task<IActionResult> ExportBitrixSyncHistoryExcel(int orderId, CancellationToken cancellationToken = defau |
| | | 1009 | | { |
| | 0 | 1010 | | var order = await GetAccessibleOrderAsync(orderId, cancellationToken); |
| | 0 | 1011 | | if (order == null) |
| | 0 | 1012 | | return NotFound(); |
| | | 1013 | | |
| | 0 | 1014 | | if (string.IsNullOrWhiteSpace(order.Article)) |
| | 0 | 1015 | | return NotFound(); |
| | | 1016 | | |
| | 0 | 1017 | | var (bytes, filename) = await BitrixStockSyncReportExcelBuilder.BuildArticleHistoryAsync( |
| | 0 | 1018 | | _bitrixSyncArticleHistoryService, |
| | 0 | 1019 | | order.Article.Trim(), |
| | 0 | 1020 | | cancellationToken); |
| | | 1021 | | |
| | 0 | 1022 | | if (bytes == null || bytes.Length == 0) |
| | 0 | 1023 | | return NotFound(); |
| | | 1024 | | |
| | 0 | 1025 | | return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename); |
| | 0 | 1026 | | } |
| | | 1027 | | |
| | | 1028 | | /// <summary>Вкладка «Фид»: цена и остатки артикула заказа в фиде и история цены по прогонам.</summary> |
| | | 1029 | | [HttpGet] |
| | | 1030 | | [PageAuthorize("Studio2.OrderHistory.GetOrderHistory")] |
| | | 1031 | | public async Task<IActionResult> GetFeedPriceStock(int orderId, CancellationToken cancellationToken = default) |
| | | 1032 | | { |
| | 0 | 1033 | | var result = await _feedPriceService.GetAsync(orderId, User, cancellationToken); |
| | 0 | 1034 | | return result is null ? NotFound() : Json(result); |
| | 0 | 1035 | | } |
| | | 1036 | | |
| | | 1037 | | /// <summary>Вкладка «Фид»: как получилась цена позиции заказа (расшифровка по сборкам кабинетов, выбранная — по клиен |
| | | 1038 | | [HttpGet] |
| | | 1039 | | [PageAuthorize("Studio2.OrderHistory.GetOrderHistory")] |
| | | 1040 | | public async Task<IActionResult> GetFeedPriceExplanation(int orderId, long? runId, CancellationToken cancellationToken |
| | | 1041 | | { |
| | 0 | 1042 | | if (runId is <= 0) return BadRequest(new { message = "runId: положительное целое число." }); |
| | | 1043 | | |
| | 0 | 1044 | | var result = await _feedPriceService.GetExplanationAsync(orderId, User, runId, cancellationToken); |
| | 0 | 1045 | | return result is null ? NotFound() : Json(result); |
| | 0 | 1046 | | } |
| | | 1047 | | |
| | | 1048 | | /// <summary> |
| | | 1049 | | /// Превью восстановления заказа к точке во времени (момент операции в истории). |
| | | 1050 | | /// Возвращает список полей, которые изменятся: текущее → целевое значение. |
| | | 1051 | | /// </summary> |
| | | 1052 | | [HttpGet] |
| | | 1053 | | [Authorize(Roles = "Admin")] |
| | | 1054 | | [PageAuthorize("Studio2.OrderHistory.GetRollbackPreview", AccessType.View)] |
| | | 1055 | | public async Task<IActionResult> GetRollbackPreview(int orderId, long pointTicks, CancellationToken cancellationToken |
| | | 1056 | | { |
| | 0 | 1057 | | var order = await GetAccessibleOrderAsync(orderId, cancellationToken); |
| | 0 | 1058 | | if (order == null) |
| | 0 | 1059 | | return Forbid(); |
| | | 1060 | | |
| | 0 | 1061 | | if (pointTicks <= 0 || pointTicks > DateTime.MaxValue.Ticks) |
| | 0 | 1062 | | return BadRequest("Некорректная точка восстановления."); |
| | | 1063 | | |
| | 0 | 1064 | | var point = new DateTime(pointTicks); |
| | 0 | 1065 | | var preview = await _rollbackService.BuildPreviewAsync(orderId, point, cancellationToken); |
| | 0 | 1066 | | if (!preview.OrderFound) |
| | 0 | 1067 | | return NotFound(); |
| | | 1068 | | |
| | 0 | 1069 | | return Json(new |
| | 0 | 1070 | | { |
| | 0 | 1071 | | orderId = preview.OrderId, |
| | 0 | 1072 | | pointLabel = point.ToString("dd.MM.yyyy HH:mm:ss"), |
| | 0 | 1073 | | hasChanges = preview.HasChanges, |
| | 0 | 1074 | | applicableCount = preview.ApplicableCount, |
| | | 1075 | | changes = preview.Changes.Select(c => new |
| | | 1076 | | { |
| | | 1077 | | field = c.DisplayName, |
| | | 1078 | | current = c.CurrentDisplay, |
| | | 1079 | | target = c.TargetDisplay, |
| | | 1080 | | applicable = c.Applicable, |
| | | 1081 | | warning = c.Warning |
| | | 1082 | | }) |
| | 0 | 1083 | | }); |
| | 0 | 1084 | | } |
| | | 1085 | | |
| | | 1086 | | /// <summary> |
| | | 1087 | | /// Применяет восстановление заказа к выбранной точке. Изменения попадают в историю |
| | | 1088 | | /// автоматически (триггер) и помечаются как <c>rollback:<пользователь></c>. |
| | | 1089 | | /// </summary> |
| | | 1090 | | [HttpPost] |
| | | 1091 | | [ValidateAntiForgeryToken] |
| | | 1092 | | [Authorize(Roles = "Admin")] |
| | | 1093 | | [PageAuthorize("Studio2.OrderHistory.ApplyRollback", AccessType.Edit)] |
| | | 1094 | | public async Task<IActionResult> ApplyRollback(int orderId, long pointTicks, CancellationToken cancellationToken = def |
| | | 1095 | | { |
| | 0 | 1096 | | var order = await GetAccessibleOrderAsync(orderId, cancellationToken); |
| | 0 | 1097 | | if (order == null) |
| | 0 | 1098 | | return Forbid(); |
| | | 1099 | | |
| | 0 | 1100 | | if (pointTicks <= 0 || pointTicks > DateTime.MaxValue.Ticks) |
| | 0 | 1101 | | return BadRequest("Некорректная точка восстановления."); |
| | | 1102 | | |
| | 0 | 1103 | | var point = new DateTime(pointTicks); |
| | 0 | 1104 | | var marker = $"rollback:{User?.Identity?.Name ?? "unknown"}"; |
| | 0 | 1105 | | var result = await _rollbackService.ApplyAsync(orderId, point, marker, cancellationToken); |
| | | 1106 | | |
| | 0 | 1107 | | return Json(new |
| | 0 | 1108 | | { |
| | 0 | 1109 | | success = result.Success, |
| | 0 | 1110 | | applied = result.AppliedCount, |
| | 0 | 1111 | | message = result.Message |
| | 0 | 1112 | | }); |
| | 0 | 1113 | | } |
| | | 1114 | | |
| | | 1115 | | private async Task<Order?> GetAccessibleOrderAsync(int orderId, CancellationToken cancellationToken) |
| | | 1116 | | { |
| | 0 | 1117 | | var query = await BuildAccessibleOrdersQueryAsync(o => o.Id == orderId, cancellationToken); |
| | 0 | 1118 | | return query is null ? null : await query.FirstOrDefaultAsync(cancellationToken); |
| | 0 | 1119 | | } |
| | | 1120 | | |
| | | 1121 | | /// <summary>Заказы, доступные пользователю по data scope и разрешённым складам. Null — пользователь не определён.</su |
| | | 1122 | | private async Task<IQueryable<Order>?> BuildAccessibleOrdersQueryAsync( |
| | | 1123 | | System.Linq.Expressions.Expression<Func<Order, bool>> predicate, CancellationToken cancellationToken) |
| | | 1124 | | { |
| | 0 | 1125 | | var userId = User?.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 1126 | | if (string.IsNullOrWhiteSpace(userId)) |
| | 0 | 1127 | | return null; |
| | | 1128 | | |
| | 0 | 1129 | | var query = _context.Orders.AsNoTracking().Where(predicate); |
| | 0 | 1130 | | query = await _dataScopeService.ApplyDataScopeAsync(query, userId, "Order", null, cancellationToken); |
| | | 1131 | | |
| | 0 | 1132 | | var allowed = await _scopeFilterValuesService.GetAllowedValuesAsync(userId, "Order", cancellationToken); |
| | 0 | 1133 | | if (allowed.TryGetValue("ShipmentWarehouseId", out var allowedWarehouseIdsRaw) && |
| | 0 | 1134 | | allowedWarehouseIdsRaw.Count > 0) |
| | | 1135 | | { |
| | 0 | 1136 | | var allowedWarehouseIds = allowedWarehouseIdsRaw |
| | | 1137 | | .Select(x => int.TryParse(x, out var id) ? id : (int?)null) |
| | | 1138 | | .Where(x => x.HasValue) |
| | | 1139 | | .Select(x => x!.Value) |
| | 0 | 1140 | | .Distinct() |
| | 0 | 1141 | | .ToArray(); |
| | | 1142 | | |
| | 0 | 1143 | | if (allowedWarehouseIds.Length > 0) |
| | | 1144 | | { |
| | 0 | 1145 | | query = query.Where(o => |
| | 0 | 1146 | | o.ShipmentWarehouseId.HasValue && |
| | 0 | 1147 | | allowedWarehouseIds.Contains(o.ShipmentWarehouseId.Value)); |
| | | 1148 | | } |
| | | 1149 | | } |
| | | 1150 | | |
| | 0 | 1151 | | return query; |
| | 0 | 1152 | | } |
| | | 1153 | | |
| | | 1154 | | private async Task<Dictionary<string, OrderHistoryUserProfileViewModel>> BuildHistoryUserProfilesAsync(List<OrderHis |
| | | 1155 | | { |
| | 0 | 1156 | | var result = new Dictionary<string, OrderHistoryUserProfileViewModel>(StringComparer.OrdinalIgnoreCase); |
| | | 1157 | | |
| | 0 | 1158 | | var displayLogins = histories |
| | | 1159 | | .Select(h => h.ChangedBy?.Trim()) |
| | | 1160 | | .Where(v => !string.IsNullOrWhiteSpace(v)) |
| | | 1161 | | .Select(v => v!.StartsWith("rollback:", StringComparison.OrdinalIgnoreCase) ? v["rollback:".Length..].Trim() |
| | | 1162 | | .Where(v => !string.IsNullOrWhiteSpace(v)) |
| | 0 | 1163 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 1164 | | .ToList(); |
| | | 1165 | | |
| | 0 | 1166 | | if (displayLogins.Count == 0) |
| | | 1167 | | { |
| | 0 | 1168 | | return result; |
| | | 1169 | | } |
| | | 1170 | | |
| | | 1171 | | // Identity сравнивает по NormalizedUserName/NormalizedEmail (не по сырым полям) — |
| | | 1172 | | // повторяем ту же нормализацию, иначе батч-запрос может не найти то, что находил |
| | | 1173 | | // последовательный FindByNameAsync/FindByEmailAsync. |
| | 0 | 1174 | | var normalizedNames = displayLogins.Select(v => _userManager.NormalizeName(v!)).ToList(); |
| | 0 | 1175 | | var normalizedEmails = displayLogins.Select(v => _userManager.NormalizeEmail(v!)).ToList(); |
| | | 1176 | | |
| | 0 | 1177 | | var users = await _userManager.Users |
| | 0 | 1178 | | .Where(u => normalizedNames.Contains(u.NormalizedUserName!) || normalizedEmails.Contains(u.NormalizedEmail!) |
| | 0 | 1179 | | .ToListAsync() |
| | 0 | 1180 | | .ConfigureAwait(false); |
| | | 1181 | | |
| | 0 | 1182 | | foreach (var displayLogin in displayLogins) |
| | | 1183 | | { |
| | 0 | 1184 | | if (result.ContainsKey(displayLogin!)) |
| | | 1185 | | { |
| | | 1186 | | continue; |
| | | 1187 | | } |
| | | 1188 | | |
| | 0 | 1189 | | var normalizedName = _userManager.NormalizeName(displayLogin!); |
| | 0 | 1190 | | var normalizedEmail = _userManager.NormalizeEmail(displayLogin!); |
| | 0 | 1191 | | var user = users.FirstOrDefault(u => |
| | 0 | 1192 | | string.Equals(u.NormalizedUserName, normalizedName, StringComparison.Ordinal) || |
| | 0 | 1193 | | string.Equals(u.NormalizedEmail, normalizedEmail, StringComparison.Ordinal)); |
| | 0 | 1194 | | if (user == null) |
| | | 1195 | | { |
| | | 1196 | | continue; |
| | | 1197 | | } |
| | | 1198 | | |
| | 0 | 1199 | | result[displayLogin!] = new OrderHistoryUserProfileViewModel |
| | 0 | 1200 | | { |
| | 0 | 1201 | | LoginOrEmail = user.Email ?? user.UserName ?? displayLogin!, |
| | 0 | 1202 | | DisplayName = user.GoogleDisplayName ?? user.UserName ?? user.Email ?? displayLogin!, |
| | 0 | 1203 | | AvatarUrl = user.GoogleAvatarUrl |
| | 0 | 1204 | | }; |
| | | 1205 | | } |
| | | 1206 | | |
| | 0 | 1207 | | return result; |
| | 0 | 1208 | | } |
| | | 1209 | | } |