| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using Microsoft.AspNetCore.Authorization; |
| | | 3 | | using Microsoft.AspNetCore.Identity; |
| | | 4 | | using Microsoft.AspNetCore.Mvc; |
| | | 5 | | using Microsoft.Extensions.Caching.Memory; |
| | | 6 | | using Microsoft.Extensions.DependencyInjection; |
| | | 7 | | using Microsoft.AspNetCore.Mvc.Rendering; |
| | | 8 | | using Newtonsoft.Json; |
| | | 9 | | using OServices.FiltersServices.FilterModels; |
| | | 10 | | using OzonDomains; |
| | | 11 | | using OzonDomains.Models; |
| | | 12 | | using OzonDomains.Models.AccessControl; |
| | | 13 | | using OzonOrdersWeb.WebServices; |
| | | 14 | | using OzonOrdersWeb.WebServices.Currency; |
| | | 15 | | using OzonOrdersWeb.WebServices.Cookies; |
| | | 16 | | using OzonOrdersWeb.ViewModels.OrderViewModels; |
| | | 17 | | using OzonRepositories.Context; |
| | | 18 | | using OzonRepositories.Context.Identity; |
| | | 19 | | using Services.ApiServices.DropBoxApi; |
| | | 20 | | using Services.ApiServices.OzonApi; |
| | | 21 | | using Services.ApiServices.YandexApi; |
| | | 22 | | using Services.YandexServices; |
| | | 23 | | using Services.CacheServices.Cache.OzonOrdersCache; |
| | | 24 | | using Services.CacheServices.Cache.UniqueValuesCache; |
| | | 25 | | using Services.CacheServices.Cache.UserCacheService; |
| | | 26 | | using Services.DataServices; |
| | | 27 | | using Services.DataServices.DTO; |
| | | 28 | | using Services.FiltersServices.DataFilterManagers; |
| | | 29 | | using Services.FiltersServices.SortModels; |
| | | 30 | | using Services.ParserServices; |
| | | 31 | | using Services.ParserServices.FielParsers; |
| | | 32 | | using Services.ParserServices.HelpDictEnum; |
| | | 33 | | using Services.PriceСlculationServices; |
| | | 34 | | using Services.ReleasServices.ReleaseManager; |
| | | 35 | | using Services.TransactionUtilsServices; |
| | | 36 | | using Services.LabelServices; |
| | | 37 | | using Services.CacheServices.Cache; |
| | | 38 | | using System.IO.Compression; |
| | | 39 | | using System.Net.Http; |
| | | 40 | | using System.Security.Claims; |
| | | 41 | | using System.Text; |
| | | 42 | | using System.Text.Json; |
| | | 43 | | using System.Diagnostics; |
| | | 44 | | using Hangfire; |
| | | 45 | | using Hangfire.States; |
| | | 46 | | using Services.HangfireService; |
| | | 47 | | using Microsoft.EntityFrameworkCore; |
| | | 48 | | using OzonDomains.Models.OrderCarts.Cart; |
| | | 49 | | using OzonRepositories.Data.Bitrix; |
| | | 50 | | using Services.ApiServices._1CApi; |
| | | 51 | | using Services.ApiServices._1CApi.Models; |
| | | 52 | | using Services.CacheServices.Cache.CartCache; |
| | | 53 | | using Services.SignalRServices; |
| | | 54 | | using SlqStudio.Application.Services.EmailService; |
| | | 55 | | using Services.ApiServices.OzonApi.Filters; |
| | | 56 | | using OzonDomains.ViewModels; |
| | | 57 | | using OzonOrdersWeb.Areas.Admin.OrderList; |
| | | 58 | | using OzonOrdersWeb.Areas.Studio2.ViewHelpers; |
| | | 59 | | using OzonOrdersWeb.Areas.Studio2.Controllers.Directories; |
| | | 60 | | using OzonOrdersWeb.Authorization; |
| | | 61 | | using OzonOrdersWeb.WebServices.Orders; |
| | | 62 | | |
| | | 63 | | |
| | | 64 | | namespace OzonOrdersWeb.Controllers |
| | | 65 | | |
| | | 66 | | { |
| | | 67 | | [Authorize(Roles = "User,Admin")] |
| | | 68 | | [Area("Studio2")] |
| | | 69 | | public partial class OrdersController : Controller |
| | | 70 | | |
| | | 71 | | { |
| | | 72 | | private const string ReturnsFilterCookieKey = "FilterDataReturns"; |
| | | 73 | | private const string ReturnsSortCookieKey = "SortStateReturns"; |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Жёсткий потолок строк на страницу списка заказов. Выше — рендер раздувает HTML до 3+ МБ |
| | | 77 | | /// и DOM до ~14k узлов на 100 строк (row-шаблон ~36 КБ/строку). Больше данных — только |
| | | 78 | | /// страницами: номера страниц и кнопка «Показать ещё» работают через AJAX без full reload. |
| | | 79 | | /// </summary> |
| | | 80 | | public const int MaxOrdersPageSize = 100; |
| | | 81 | | |
| | | 82 | | private const int DefaultOrdersPageSize = 15; |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// Определяет строк на страницу: <paramref name="overrideSize"/> (если задан в этом же запросе, |
| | | 86 | | /// когда cookie ещё не долетел до Request) иначе cookie PageSize. Всегда в [1..<see cref="MaxOrdersPageSize"/>] |
| | | 87 | | /// </summary> |
| | | 88 | | private int ResolveOrdersPageSize(int? overrideSize = null) |
| | | 89 | | { |
| | 0 | 90 | | var size = overrideSize is > 0 |
| | 0 | 91 | | ? overrideSize.Value |
| | 0 | 92 | | : (int.TryParse(Request.Cookies["PageSize"], out var s) && s > 0 ? s : DefaultOrdersPageSize); |
| | 0 | 93 | | return Math.Clamp(size, 1, MaxOrdersPageSize); |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | private readonly ApplicationDbContext _context; |
| | | 97 | | |
| | | 98 | | private readonly IMemoryCache _memoryCache; |
| | | 99 | | |
| | | 100 | | private readonly OrdersDataServices _orderServices; |
| | | 101 | | |
| | | 102 | | private readonly AppStatusDataServices _appStatusServices; |
| | | 103 | | |
| | | 104 | | private readonly ClientStatusDataServices _clientStatusServices; |
| | | 105 | | |
| | | 106 | | private readonly SupplierDataServices _supplierDataServices; |
| | | 107 | | |
| | | 108 | | private readonly WarehouseDataServices _warehouseDataServices; |
| | | 109 | | |
| | | 110 | | private readonly OrderCaster _orderCaster; |
| | | 111 | | |
| | | 112 | | private readonly OrderCache _cache; |
| | | 113 | | |
| | | 114 | | private readonly OrderDataFilterManager _dataFilterManager; |
| | | 115 | | |
| | | 116 | | private readonly CacheUpdater<Order> _cacheUpdater; |
| | | 117 | | |
| | | 118 | | private readonly OzonJsonDataBuilder _jsonDataBuilder; |
| | | 119 | | |
| | | 120 | | private readonly ReleaseManager _releaseManager; |
| | | 121 | | |
| | | 122 | | private readonly TransactionDataServices _transactionDataServices; |
| | | 123 | | |
| | | 124 | | private readonly TransactionCache _transactionCache; |
| | | 125 | | |
| | | 126 | | private readonly DuplicateOrdersServices _duplicateOrdersServices; |
| | | 127 | | |
| | | 128 | | private readonly OzonClientServices _ozonClientServices; |
| | | 129 | | |
| | | 130 | | private readonly ExcelParser _excelParser; |
| | | 131 | | |
| | | 132 | | private readonly ColumnMappingDataServices _columnMappingDataServices; |
| | | 133 | | |
| | | 134 | | private readonly CurrencyRateFetcher _currencyRateFetcher; |
| | | 135 | | |
| | | 136 | | private readonly ICurrencyRatesViewBagService _currencyRatesViewBagService; |
| | | 137 | | |
| | | 138 | | private readonly DropboxApiClient _dropboxApiClient; |
| | | 139 | | |
| | | 140 | | private readonly ILabelFileStorage _labelFileStorage; |
| | | 141 | | |
| | | 142 | | private readonly ManufacturerDataService _manufacturerDataService; |
| | | 143 | | |
| | | 144 | | private readonly ExcelExporter _excelExporter; |
| | | 145 | | |
| | | 146 | | private readonly AccessProfileDataServices _accessProfileDataServices; |
| | | 147 | | |
| | | 148 | | private readonly YandexDataManager _yandexDataManager; |
| | | 149 | | private readonly IYandexOrderStatusSyncService _yandexOrderStatusSyncService; |
| | | 150 | | |
| | | 151 | | private readonly IUserCacheService _userCacheService; |
| | | 152 | | |
| | | 153 | | private readonly OrderCartServices _orderCartServices; |
| | | 154 | | |
| | | 155 | | private readonly CartCache _cartCache; |
| | | 156 | | |
| | | 157 | | private readonly EtProducerDataServices _etProducerDataServices; |
| | | 158 | | |
| | | 159 | | private readonly DeliveryDataServices _deliveryDataServices; |
| | | 160 | | |
| | | 161 | | private static string SanitizeFileName(string name) |
| | | 162 | | { |
| | 0 | 163 | | if (string.IsNullOrWhiteSpace(name)) |
| | 0 | 164 | | return "Client"; |
| | | 165 | | |
| | 0 | 166 | | var invalidChars = Path.GetInvalidFileNameChars(); |
| | 0 | 167 | | var cleaned = new string(name.Select(ch => invalidChars.Contains(ch) ? '_' : ch).ToArray()); |
| | 0 | 168 | | return string.IsNullOrWhiteSpace(cleaned) ? "Client" : cleaned; |
| | | 169 | | } |
| | | 170 | | |
| | | 171 | | private readonly OzonApiDataManager _ozonApiDataManager; |
| | | 172 | | |
| | | 173 | | private readonly OzonRepositories.Authorization.IUserScopeProvider _userScopeProvider; |
| | | 174 | | |
| | | 175 | | private readonly Services.Authorization.Services.IPermissionService _permissionService; |
| | | 176 | | |
| | 0 | 177 | | private readonly OzonLabelSessionStore _ozonLabelSessionStore = new(); |
| | | 178 | | |
| | | 179 | | private readonly IOzonLabelPrintService _ozonLabelPrintService; |
| | | 180 | | |
| | | 181 | | private readonly ILabelExistenceService _labelExistenceService; |
| | | 182 | | |
| | | 183 | | private readonly ILabelPrintLogService _labelPrintLogService; |
| | | 184 | | |
| | | 185 | | private readonly IOrderFilterListsService _orderFilterListsService; |
| | | 186 | | |
| | | 187 | | private readonly IOrdersIndexQueryService _ordersIndexQueryService; |
| | | 188 | | |
| | | 189 | | private readonly IOrderDataScopeQueryApplier _dataScopeApplier; |
| | | 190 | | |
| | | 191 | | private readonly IOrdersIndexPageDetailsService _ordersIndexPageDetailsService; |
| | | 192 | | |
| | | 193 | | private readonly IOrderReturnInfoService _orderReturnInfoService; |
| | | 194 | | |
| | | 195 | | private readonly IOrdersClientStatusSyncService _clientStatusSyncService; |
| | | 196 | | |
| | | 197 | | private readonly IOrdersIndexClientStatusRefreshService _indexClientStatusRefreshService; |
| | | 198 | | |
| | | 199 | | private readonly IOrdersIndexViewModelEnricher _ordersIndexViewModelEnricher; |
| | | 200 | | |
| | | 201 | | private readonly IOrdersIndexPageViewDataService _ordersIndexPageViewDataService; |
| | | 202 | | |
| | | 203 | | private readonly IOrderDataScopeIdFilterService _dataScopeIdFilterService; |
| | | 204 | | |
| | | 205 | | private readonly IOrdersOzonShipService _ozonShipService; |
| | | 206 | | |
| | | 207 | | private readonly IOzonExemplarService _ozonExemplarService; |
| | | 208 | | |
| | | 209 | | private readonly IOrderCreateFormService _orderCreateFormService; |
| | | 210 | | |
| | | 211 | | private readonly Services.OzonHandoverServices.IOzonHandoverImportService _handoverImportService; |
| | | 212 | | |
| | | 213 | | |
| | 0 | 214 | | public OrdersController(ApplicationDbContext context, |
| | 0 | 215 | | IMemoryCache memoryCache, |
| | 0 | 216 | | OrdersDataServices orderRepository, |
| | 0 | 217 | | AppStatusDataServices appStatusDataServices, |
| | 0 | 218 | | ClientStatusDataServices clientStatusDataServices, |
| | 0 | 219 | | SupplierDataServices supplierDataServices, |
| | 0 | 220 | | WarehouseDataServices warehouseDataServices, |
| | 0 | 221 | | OrderCaster orderCaster, |
| | 0 | 222 | | OrderCache orderCache, |
| | 0 | 223 | | OrderDataFilterManager dataFilterManager, |
| | 0 | 224 | | CacheUpdater<Order> cacheUpdater, |
| | 0 | 225 | | OzonJsonDataBuilder jsonDataBuilder, |
| | 0 | 226 | | ReleaseManager releaseManager, |
| | 0 | 227 | | TransactionDataServices transactionDataServices, |
| | 0 | 228 | | TransactionCache transactionCache, |
| | 0 | 229 | | DuplicateOrdersServices duplicateOrdersServices, |
| | 0 | 230 | | OzonClientServices ozonClientServices, |
| | 0 | 231 | | ExcelParser excelParser, |
| | 0 | 232 | | ColumnMappingDataServices columnMappingDataServices, |
| | 0 | 233 | | CurrencyRateFetcher currencyRateFetcher, |
| | 0 | 234 | | ICurrencyRatesViewBagService currencyRatesViewBagService, |
| | 0 | 235 | | DropboxApiClient dropboxApiClient, |
| | 0 | 236 | | ILabelFileStorage labelFileStorage, |
| | 0 | 237 | | ManufacturerDataService manufacturerDataService, |
| | 0 | 238 | | ExcelExporter excelExporter, |
| | 0 | 239 | | AccessProfileDataServices accessProfileDataServices, |
| | 0 | 240 | | YandexDataManager yandexDataManager, |
| | 0 | 241 | | IYandexOrderStatusSyncService yandexOrderStatusSyncService, |
| | 0 | 242 | | IUserCacheService userCacheService, |
| | 0 | 243 | | OrderCartServices orderCartServices, |
| | 0 | 244 | | CartCache cartCache, |
| | 0 | 245 | | EtProducerDataServices etProducerDataServices, |
| | 0 | 246 | | DeliveryDataServices deliveryDataServices, |
| | 0 | 247 | | OzonApiDataManager ozonApiDataManager, |
| | 0 | 248 | | OzonRepositories.Authorization.IUserScopeProvider userScopeProvider, |
| | 0 | 249 | | Services.Authorization.Services.IPermissionService permissionService, |
| | 0 | 250 | | IOzonLabelPrintService ozonLabelPrintService, |
| | 0 | 251 | | ILabelExistenceService labelExistenceService, |
| | 0 | 252 | | ILabelPrintLogService labelPrintLogService, |
| | 0 | 253 | | IOrderFilterListsService orderFilterListsService, |
| | 0 | 254 | | IOrdersIndexQueryService ordersIndexQueryService, |
| | 0 | 255 | | IOrderDataScopeQueryApplier dataScopeApplier, |
| | 0 | 256 | | IOrdersIndexPageDetailsService ordersIndexPageDetailsService, |
| | 0 | 257 | | IOrderReturnInfoService orderReturnInfoService, |
| | 0 | 258 | | IOrdersClientStatusSyncService clientStatusSyncService, |
| | 0 | 259 | | IOrdersIndexClientStatusRefreshService indexClientStatusRefreshService, |
| | 0 | 260 | | IOrdersIndexViewModelEnricher ordersIndexViewModelEnricher, |
| | 0 | 261 | | IOrdersIndexPageViewDataService ordersIndexPageViewDataService, |
| | 0 | 262 | | IOrderDataScopeIdFilterService dataScopeIdFilterService, |
| | 0 | 263 | | IOrdersOzonShipService ozonShipService, |
| | 0 | 264 | | IOzonExemplarService ozonExemplarService, |
| | 0 | 265 | | IOrderCreateFormService orderCreateFormService, |
| | 0 | 266 | | Services.OzonHandoverServices.IOzonHandoverImportService handoverImportService) |
| | | 267 | | |
| | | 268 | | { |
| | 0 | 269 | | _context = context; |
| | 0 | 270 | | _memoryCache = memoryCache; |
| | | 271 | | |
| | 0 | 272 | | _orderServices = orderRepository; |
| | | 273 | | |
| | 0 | 274 | | _appStatusServices = appStatusDataServices; |
| | | 275 | | |
| | 0 | 276 | | _clientStatusServices = clientStatusDataServices; |
| | | 277 | | |
| | 0 | 278 | | _supplierDataServices = supplierDataServices; |
| | | 279 | | |
| | 0 | 280 | | _warehouseDataServices = warehouseDataServices; |
| | | 281 | | |
| | 0 | 282 | | _orderCaster = orderCaster; |
| | | 283 | | |
| | 0 | 284 | | _cache = orderCache; |
| | | 285 | | |
| | 0 | 286 | | _dataFilterManager = dataFilterManager; |
| | | 287 | | |
| | 0 | 288 | | _cacheUpdater = cacheUpdater; |
| | | 289 | | |
| | 0 | 290 | | _jsonDataBuilder = jsonDataBuilder; |
| | | 291 | | |
| | 0 | 292 | | _releaseManager = releaseManager; |
| | | 293 | | |
| | 0 | 294 | | _transactionDataServices = transactionDataServices; |
| | | 295 | | |
| | 0 | 296 | | _transactionCache = transactionCache; |
| | | 297 | | |
| | 0 | 298 | | _duplicateOrdersServices = duplicateOrdersServices; |
| | | 299 | | |
| | 0 | 300 | | _ozonClientServices = ozonClientServices; |
| | | 301 | | |
| | 0 | 302 | | _excelParser = excelParser; |
| | | 303 | | |
| | 0 | 304 | | _columnMappingDataServices = columnMappingDataServices; |
| | | 305 | | |
| | 0 | 306 | | _currencyRateFetcher = currencyRateFetcher; |
| | | 307 | | |
| | 0 | 308 | | _currencyRatesViewBagService = currencyRatesViewBagService; |
| | | 309 | | |
| | 0 | 310 | | _dropboxApiClient = dropboxApiClient; |
| | | 311 | | |
| | 0 | 312 | | _labelFileStorage = labelFileStorage; |
| | | 313 | | |
| | 0 | 314 | | _manufacturerDataService = manufacturerDataService; |
| | | 315 | | |
| | 0 | 316 | | _excelExporter = excelExporter; |
| | | 317 | | |
| | 0 | 318 | | _accessProfileDataServices = accessProfileDataServices; |
| | | 319 | | |
| | 0 | 320 | | _yandexDataManager = yandexDataManager; |
| | 0 | 321 | | _yandexOrderStatusSyncService = yandexOrderStatusSyncService; |
| | | 322 | | |
| | 0 | 323 | | _userCacheService = userCacheService; |
| | | 324 | | |
| | 0 | 325 | | _orderCartServices = orderCartServices; |
| | | 326 | | |
| | 0 | 327 | | _cartCache = cartCache; |
| | | 328 | | |
| | 0 | 329 | | _etProducerDataServices = etProducerDataServices; |
| | | 330 | | |
| | 0 | 331 | | _deliveryDataServices = deliveryDataServices; |
| | | 332 | | |
| | 0 | 333 | | _warehouseDataServices = warehouseDataServices; |
| | | 334 | | |
| | 0 | 335 | | _ozonApiDataManager = ozonApiDataManager; |
| | | 336 | | |
| | 0 | 337 | | _userScopeProvider = userScopeProvider; |
| | | 338 | | |
| | 0 | 339 | | _permissionService = permissionService; |
| | | 340 | | |
| | 0 | 341 | | _ozonLabelPrintService = ozonLabelPrintService; |
| | 0 | 342 | | _labelExistenceService = labelExistenceService; |
| | 0 | 343 | | _labelPrintLogService = labelPrintLogService; |
| | 0 | 344 | | _orderFilterListsService = orderFilterListsService; |
| | 0 | 345 | | _ordersIndexQueryService = ordersIndexQueryService; |
| | 0 | 346 | | _dataScopeApplier = dataScopeApplier; |
| | 0 | 347 | | _ordersIndexPageDetailsService = ordersIndexPageDetailsService; |
| | 0 | 348 | | _orderReturnInfoService = orderReturnInfoService; |
| | 0 | 349 | | _clientStatusSyncService = clientStatusSyncService; |
| | 0 | 350 | | _indexClientStatusRefreshService = indexClientStatusRefreshService; |
| | 0 | 351 | | _ordersIndexViewModelEnricher = ordersIndexViewModelEnricher; |
| | 0 | 352 | | _ordersIndexPageViewDataService = ordersIndexPageViewDataService; |
| | 0 | 353 | | _dataScopeIdFilterService = dataScopeIdFilterService; |
| | 0 | 354 | | _ozonShipService = ozonShipService; |
| | 0 | 355 | | _ozonExemplarService = ozonExemplarService; |
| | 0 | 356 | | _orderCreateFormService = orderCreateFormService; |
| | 0 | 357 | | _handoverImportService = handoverImportService; |
| | 0 | 358 | | } |
| | | 359 | | |
| | | 360 | | private async Task<IReadOnlyDictionary<string, bool>> BuildOrderListFieldReadMapAsync(string userId, Cancellatio |
| | | 361 | | { |
| | 0 | 362 | | return await OrderListFieldReadAccessBuilder.FromUserIdAsync(_permissionService, userId, ct); |
| | 0 | 363 | | } |
| | | 364 | | |
| | | 365 | | private static IReadOnlyDictionary<string, bool> BuildOrderListFieldReadMapFromBundle( |
| | | 366 | | Services.Authorization.Dtos.UserPermissionsBundle bundle) |
| | | 367 | | { |
| | 0 | 368 | | return OrderListFieldReadAccessBuilder.FromBundle(bundle); |
| | | 369 | | } |
| | | 370 | | |
| | | 371 | | |
| | | 372 | | // Без ResponseCache: HTML персонализирован (RLS, cookies фильтров, этикетки Dropbox). |
| | | 373 | | public async Task<IActionResult> Returns(OrderSortState sortOrder = OrderSortState.StandardState, int page = 1) |
| | | 374 | | |
| | | 375 | | { |
| | 0 | 376 | | var user = await _userCacheService.GetCachedUserAsync(User); |
| | 0 | 377 | | NormalizeSyntheticAccessProfile(user); |
| | | 378 | | |
| | 0 | 379 | | AccessProfile? accessProfile = null; |
| | | 380 | | |
| | 0 | 381 | | if (user?.AccessProfileId != null) |
| | | 382 | | |
| | | 383 | | { |
| | 0 | 384 | | accessProfile = await _accessProfileDataServices.GetAccessProfileAsync(user.AccessProfileId.Value); |
| | | 385 | | } |
| | | 386 | | |
| | | 387 | | |
| | 0 | 388 | | var isAdmin = User.IsInRole("Admin"); |
| | 0 | 389 | | ViewBag.IsAdmin = isAdmin; |
| | | 390 | | |
| | 0 | 391 | | SaveSortStateCookie(sortOrder, ReturnsSortCookieKey); |
| | 0 | 392 | | SetInfoMessage(); |
| | | 393 | | |
| | 0 | 394 | | string? filterDataString = HttpContext.Request.Cookies[ReturnsFilterCookieKey]; |
| | | 395 | | |
| | 0 | 396 | | var filterData = new OrderFilterModel |
| | 0 | 397 | | { |
| | 0 | 398 | | OnlyWithReturns = true |
| | 0 | 399 | | }; |
| | | 400 | | |
| | 0 | 401 | | bool hasFilters = false; |
| | | 402 | | |
| | 0 | 403 | | if (!string.IsNullOrEmpty(filterDataString)) |
| | | 404 | | |
| | | 405 | | { |
| | 0 | 406 | | filterData = JsonConvert.DeserializeObject<OrderFilterModel>(filterDataString) ?? new OrderFilterModel() |
| | 0 | 407 | | filterData.OnlyWithReturns = true; |
| | | 408 | | |
| | 0 | 409 | | hasFilters = !_dataFilterManager.AreAllPropertiesNull(filterData); |
| | | 410 | | |
| | 0 | 411 | | if (!string.IsNullOrEmpty(filterData.Barcode)) |
| | | 412 | | |
| | | 413 | | { |
| | 0 | 414 | | ViewData["SearchByBarcode"] = true; |
| | | 415 | | |
| | 0 | 416 | | ViewData["BarcodeValue"] = filterData.Barcode; |
| | | 417 | | } |
| | | 418 | | } |
| | | 419 | | |
| | 0 | 420 | | int pageSize = ResolveOrdersPageSize(); |
| | | 421 | | |
| | 0 | 422 | | if (page < 1) |
| | | 423 | | |
| | 0 | 424 | | page = 1; |
| | | 425 | | |
| | 0 | 426 | | bool hasUserAccessRestrictions = (accessProfile != null && accessProfile.ScopeItems.Any()) |
| | 0 | 427 | | || !string.IsNullOrEmpty(_userScopeProvider.GetFilterExpression("Order")); |
| | | 428 | | |
| | 0 | 429 | | if (sortOrder == OrderSortState.StandardState && Request.Cookies.ContainsKey(ReturnsSortCookieKey)) |
| | | 430 | | { |
| | 0 | 431 | | sortOrder = GetSortStateCookie(ReturnsSortCookieKey); |
| | | 432 | | } |
| | | 433 | | |
| | 0 | 434 | | var indexQueryResult = await LoadOrdersIndexPageAsync( |
| | 0 | 435 | | filterData, page, pageSize, sortOrder, accessProfile, hasFilters, hasUserAccessRestrictions, |
| | 0 | 436 | | isReturnsListPage: true); |
| | 0 | 437 | | var totalOrdersCount = indexQueryResult.TotalCount; |
| | | 438 | | |
| | 0 | 439 | | var filterListsByData = HttpContext.Request.Cookies["FilterListsByData"] == "true"; |
| | | 440 | | |
| | 0 | 441 | | await ApplyFilterListsToViewAsync( |
| | 0 | 442 | | filterListsByData ? indexQueryResult.Orders : null, |
| | 0 | 443 | | accessProfile, |
| | 0 | 444 | | filterListsByData); |
| | | 445 | | |
| | 0 | 446 | | SetSortOrderViewData(sortOrder); |
| | | 447 | | |
| | 0 | 448 | | var (distinctOrders, ordersForPage) = ShapeOrdersAfterLoad( |
| | 0 | 449 | | indexQueryResult.Orders, |
| | 0 | 450 | | indexQueryResult.RequiresInMemorySort, |
| | 0 | 451 | | sortOrder, |
| | 0 | 452 | | filterData, |
| | 0 | 453 | | pageSize); |
| | | 454 | | |
| | 0 | 455 | | if (filterData.SyncClientStatusesOnLoad && ordersForPage.Count > 0) |
| | | 456 | | { |
| | 0 | 457 | | await _indexClientStatusRefreshService.RefreshOnPageLoadAsync( |
| | 0 | 458 | | distinctOrders, |
| | | 459 | | ordersForPage.Select(o => o.Id).Distinct().ToArray(), |
| | 0 | 460 | | HttpContext.RequestAborted); |
| | | 461 | | } |
| | | 462 | | |
| | 0 | 463 | | await _ordersIndexPageDetailsService.LoadOrderDetailsForPageAsync( |
| | 0 | 464 | | ordersForPage, accessProfile, HttpContext.RequestAborted); |
| | | 465 | | |
| | | 466 | | const int viewModelPage = 1; |
| | 0 | 467 | | var pageViewModel = new OrderPageViewModel<Order, OrderFilterModel>( |
| | 0 | 468 | | distinctOrders, |
| | 0 | 469 | | viewModelPage, pageSize, filterData, returnableCount: 0); |
| | | 470 | | |
| | 0 | 471 | | _ordersIndexPageDetailsService.ApplyDbPagination(pageViewModel, totalOrdersCount, page, pageSize); |
| | | 472 | | |
| | 0 | 473 | | await _ordersIndexPageDetailsService.PopulateUniqueCountsAsync( |
| | 0 | 474 | | pageViewModel, ordersForPage, filterData.IncludeArchived, HttpContext.RequestAborted); |
| | | 475 | | |
| | 0 | 476 | | if (user == null) |
| | | 477 | | { |
| | 0 | 478 | | return Redirect("/Identity/Account/Login"); |
| | | 479 | | } |
| | | 480 | | |
| | 0 | 481 | | pageViewModel.User = user; |
| | | 482 | | |
| | 0 | 483 | | var enrichResult = await _ordersIndexViewModelEnricher.EnrichAsync(new OrdersIndexViewModelEnrichRequest |
| | 0 | 484 | | { |
| | 0 | 485 | | ViewModel = pageViewModel, |
| | 0 | 486 | | User = user, |
| | 0 | 487 | | AccessProfile = accessProfile, |
| | 0 | 488 | | OrdersForPage = ordersForPage, |
| | 0 | 489 | | IsAdmin = isAdmin, |
| | 0 | 490 | | CancellationToken = HttpContext.RequestAborted |
| | 0 | 491 | | }); |
| | | 492 | | |
| | 0 | 493 | | await ApplyOrdersIndexPageViewDataAsync( |
| | 0 | 494 | | user.Id, isAdmin, HttpContext.RequestAborted, enrichResult.PermissionBundle); |
| | 0 | 495 | | ViewBag.ReturnVisualStatusOptions = OzonStatus.ReturnVisualStatuses; |
| | 0 | 496 | | ViewBag.ReturnWarehouseOptions = await _orderReturnInfoService.GetWarehouseOptionsAsync(HttpContext.RequestA |
| | | 497 | | |
| | 0 | 498 | | ViewData["IndexAction"] = "Returns"; |
| | 0 | 499 | | ViewData["PaginationAction"] = "Returns"; |
| | 0 | 500 | | ViewData["PaginationController"] = "Orders"; |
| | | 501 | | |
| | 0 | 502 | | ViewData["LabelExistsByShipmentNumber"] = pageViewModel.LabelExistsByShipmentNumber; |
| | | 503 | | |
| | 0 | 504 | | return View("~/Areas/Studio2/Views/Orders/ReturnsIndex.cshtml", pageViewModel); |
| | 0 | 505 | | } |
| | | 506 | | |
| | | 507 | | [HttpPost] |
| | | 508 | | public async Task<IActionResult> Returns(OrderFilterModel filterData, int page = 1, string buttonState = "", |
| | | 509 | | string clearSort = "") |
| | | 510 | | |
| | | 511 | | { |
| | 0 | 512 | | await Task.CompletedTask; |
| | 0 | 513 | | if (!string.IsNullOrEmpty(clearSort) && clearSort.ToLower() == "true") |
| | | 514 | | |
| | | 515 | | { |
| | 0 | 516 | | Response.Cookies.Delete(ReturnsSortCookieKey); |
| | 0 | 517 | | Response.Cookies.Append(ReturnsSortCookieKey, OrderSortState.StandardState.ToString()); |
| | | 518 | | } |
| | | 519 | | |
| | 0 | 520 | | filterData.OnlyWithReturns = true; |
| | | 521 | | |
| | 0 | 522 | | var serializedFilterData = JsonConvert.SerializeObject(filterData); |
| | 0 | 523 | | HttpContext.Response.Cookies.Append(ReturnsFilterCookieKey, serializedFilterData); |
| | | 524 | | |
| | 0 | 525 | | return RedirectToAction(nameof(Returns), new { page = page }); |
| | 0 | 526 | | } |
| | | 527 | | |
| | | 528 | | public async Task<IActionResult> Index(OrderSortState sortOrder = OrderSortState.StandardState, int page = 1, |
| | | 529 | | string? search = null, string? shipmentNumber = null) |
| | | 530 | | |
| | | 531 | | { |
| | 0 | 532 | | var user = await _userCacheService.GetCachedUserAsync(User); |
| | 0 | 533 | | NormalizeSyntheticAccessProfile(user); |
| | | 534 | | |
| | 0 | 535 | | AccessProfile? accessProfile = null; |
| | | 536 | | |
| | 0 | 537 | | if (user?.AccessProfileId != null) |
| | | 538 | | |
| | | 539 | | { |
| | 0 | 540 | | accessProfile = await _accessProfileDataServices.GetAccessProfileAsync(user.AccessProfileId.Value); |
| | | 541 | | } |
| | | 542 | | |
| | | 543 | | |
| | | 544 | | // Проверяем, является ли пользователь админом |
| | | 545 | | |
| | 0 | 546 | | var isAdmin = User.IsInRole("Admin"); |
| | | 547 | | |
| | | 548 | | |
| | | 549 | | // Передаём информацию о том, является ли пользователь админом |
| | | 550 | | |
| | 0 | 551 | | ViewBag.IsAdmin = isAdmin; |
| | | 552 | | |
| | | 553 | | // Права пользователя грузятся параллельно с конвейером заказов: PermissionService |
| | | 554 | | // работает через собственный IDbContextFactory + memcache (не делит scoped ApplicationDbContext), |
| | | 555 | | // поэтому запуск задачи здесь безопасен. На cache-hit — мгновенно, на cold path перекрывает |
| | | 556 | | // ~8 запросов загрузки заказов. |
| | 0 | 557 | | Task<Services.Authorization.Dtos.UserPermissionsBundle>? permissionBundleTask = |
| | 0 | 558 | | (user != null && !isAdmin) |
| | 0 | 559 | | ? _permissionService.GetUserPermissionsAsync(user.Id, HttpContext.RequestAborted) |
| | 0 | 560 | | : null; |
| | | 561 | | |
| | | 562 | | |
| | 0 | 563 | | SaveSortStateCookie(sortOrder); |
| | | 564 | | |
| | | 565 | | |
| | 0 | 566 | | SetInfoMessage(); |
| | | 567 | | |
| | | 568 | | |
| | 0 | 569 | | string? filterDataString = HttpContext.Request.Cookies["FilterData"]; |
| | | 570 | | |
| | 0 | 571 | | var filterData = new OrderFilterModel(); |
| | | 572 | | |
| | 0 | 573 | | bool hasFilters = false; |
| | | 574 | | |
| | 0 | 575 | | var globalSearch = string.IsNullOrWhiteSpace(search) ? null : search.Trim(); |
| | 0 | 576 | | var shipmentNumberFilter = string.IsNullOrWhiteSpace(shipmentNumber) ? null : shipmentNumber.Trim(); |
| | 0 | 577 | | if (!string.IsNullOrEmpty(globalSearch)) |
| | | 578 | | { |
| | 0 | 579 | | page = 1; |
| | 0 | 580 | | filterData = new OrderFilterModel |
| | 0 | 581 | | { |
| | 0 | 582 | | Search = globalSearch, |
| | 0 | 583 | | GroupByShipment = true |
| | 0 | 584 | | }; |
| | 0 | 585 | | hasFilters = true; |
| | 0 | 586 | | HttpContext.Response.Cookies.Append("FilterData", JsonConvert.SerializeObject(filterData)); |
| | 0 | 587 | | ViewData["GlobalSearchQuery"] = globalSearch; |
| | | 588 | | } |
| | 0 | 589 | | else if (!string.IsNullOrEmpty(shipmentNumberFilter)) |
| | | 590 | | { |
| | 0 | 591 | | page = 1; |
| | 0 | 592 | | filterData = new OrderFilterModel |
| | 0 | 593 | | { |
| | 0 | 594 | | ShipmentNumber = shipmentNumberFilter, |
| | 0 | 595 | | GroupByShipment = true |
| | 0 | 596 | | }; |
| | 0 | 597 | | hasFilters = true; |
| | 0 | 598 | | HttpContext.Response.Cookies.Append("FilterData", JsonConvert.SerializeObject(filterData)); |
| | | 599 | | } |
| | 0 | 600 | | else if (!string.IsNullOrEmpty(filterDataString)) |
| | | 601 | | |
| | | 602 | | { |
| | 0 | 603 | | filterData = JsonConvert.DeserializeObject<OrderFilterModel>(filterDataString) ?? new OrderFilterModel() |
| | | 604 | | |
| | 0 | 605 | | hasFilters = !_dataFilterManager.AreAllPropertiesNull(filterData); |
| | | 606 | | |
| | | 607 | | |
| | | 608 | | // Проверяем, был ли поиск по штрихкоду (EAN) |
| | | 609 | | |
| | 0 | 610 | | if (!string.IsNullOrEmpty(filterData.Barcode)) |
| | | 611 | | |
| | | 612 | | { |
| | 0 | 613 | | ViewData["SearchByBarcode"] = true; |
| | | 614 | | |
| | 0 | 615 | | ViewData["BarcodeValue"] = filterData.Barcode; |
| | | 616 | | } |
| | | 617 | | } |
| | | 618 | | |
| | 0 | 619 | | int pageSize = ResolveOrdersPageSize(); |
| | 0 | 620 | | bool disablePagination = false; |
| | | 621 | | |
| | | 622 | | // Поиск по нескольким номерам заказов: раньше грузили всё одной страницей (pageSize=1000). |
| | | 623 | | // Теперь — обычными страницами по MaxOrdersPageSize; счётчик «найдено X из Y» остаётся, |
| | | 624 | | // пользователь листает результат номерами страниц / «Показать ещё». |
| | 0 | 625 | | if (!string.IsNullOrWhiteSpace(filterData.ShipmentNumber) && |
| | 0 | 626 | | OrderDataFilterManager.HasMultipleShipmentNumbers(filterData.ShipmentNumber)) |
| | | 627 | | { |
| | 0 | 628 | | page = page < 1 ? 1 : page; |
| | | 629 | | } |
| | | 630 | | |
| | | 631 | | // Защита от некорректных значений page (должно быть >= 1) |
| | | 632 | | |
| | 0 | 633 | | if (page < 1) |
| | | 634 | | |
| | 0 | 635 | | page = 1; |
| | | 636 | | |
| | | 637 | | |
| | 0 | 638 | | bool hasUserAccessRestrictions = (accessProfile != null && accessProfile.ScopeItems.Any()) |
| | 0 | 639 | | || !string.IsNullOrEmpty(_userScopeProvider.GetFilterExpression("Order")); |
| | | 640 | | |
| | | 641 | | // Определяем sortOrder заранее для использования в DB-level сортировке |
| | 0 | 642 | | if (sortOrder == OrderSortState.StandardState && Request.Cookies.ContainsKey("SortState")) |
| | | 643 | | { |
| | 0 | 644 | | sortOrder = GetSortStateCookie(); |
| | | 645 | | } |
| | | 646 | | |
| | 0 | 647 | | var indexQueryResult = await LoadOrdersIndexPageAsync( |
| | 0 | 648 | | filterData, page, pageSize, sortOrder, accessProfile, hasFilters, hasUserAccessRestrictions); |
| | 0 | 649 | | var totalOrdersCount = indexQueryResult.TotalCount; |
| | | 650 | | |
| | | 651 | | |
| | | 652 | | // Формируем списки для фильтров (проверяем настройку фильтрации) |
| | | 653 | | |
| | 0 | 654 | | var filterListsByData = HttpContext.Request.Cookies["FilterListsByData"] == "true"; |
| | | 655 | | |
| | 0 | 656 | | await ApplyFilterListsToViewAsync( |
| | 0 | 657 | | filterListsByData ? indexQueryResult.Orders : null, |
| | 0 | 658 | | accessProfile, |
| | 0 | 659 | | filterListsByData); |
| | | 660 | | |
| | | 661 | | // Подрезаем dropdown-списки под DataScope-ы текущего пользователя (для новой системы авторизации) |
| | | 662 | | |
| | | 663 | | |
| | 0 | 664 | | SetSortOrderViewData(sortOrder); |
| | | 665 | | |
| | 0 | 666 | | var (distinctOrders, ordersForPage) = ShapeOrdersAfterLoad( |
| | 0 | 667 | | indexQueryResult.Orders, |
| | 0 | 668 | | indexQueryResult.RequiresInMemorySort, |
| | 0 | 669 | | sortOrder, |
| | 0 | 670 | | filterData, |
| | 0 | 671 | | pageSize); |
| | | 672 | | |
| | | 673 | | // Авто-синхронизация статусов клиента только для заказов на текущей странице, |
| | | 674 | | // чтобы не перегружать внешние API. Выполняется только если включён флаг. |
| | 0 | 675 | | if (filterData.SyncClientStatusesOnLoad && ordersForPage.Count > 0) |
| | | 676 | | { |
| | 0 | 677 | | await _indexClientStatusRefreshService.RefreshOnPageLoadAsync( |
| | 0 | 678 | | distinctOrders, |
| | | 679 | | ordersForPage.Select(o => o.Id).Distinct().ToArray(), |
| | 0 | 680 | | HttpContext.RequestAborted); |
| | | 681 | | } |
| | | 682 | | |
| | 0 | 683 | | await _ordersIndexPageDetailsService.LoadOrderDetailsForPageAsync( |
| | 0 | 684 | | ordersForPage, accessProfile, HttpContext.RequestAborted); |
| | | 685 | | |
| | | 686 | | const int viewModelPage = 1; |
| | 0 | 687 | | var pageViewModel = new OrderPageViewModel<Order, OrderFilterModel>( |
| | 0 | 688 | | distinctOrders, |
| | 0 | 689 | | viewModelPage, pageSize, filterData, returnableCount: 0); |
| | | 690 | | |
| | 0 | 691 | | _ordersIndexPageDetailsService.ApplyDbPagination( |
| | 0 | 692 | | pageViewModel, totalOrdersCount, page, pageSize, disablePagination); |
| | | 693 | | |
| | 0 | 694 | | await _ordersIndexPageDetailsService.PopulateUniqueCountsAsync( |
| | 0 | 695 | | pageViewModel, ordersForPage, filterData.IncludeArchived, HttpContext.RequestAborted); |
| | | 696 | | |
| | 0 | 697 | | if (user == null) |
| | | 698 | | |
| | | 699 | | { |
| | 0 | 700 | | return Redirect("/Identity/Account/Login"); |
| | | 701 | | } |
| | | 702 | | |
| | 0 | 703 | | pageViewModel.User = user; |
| | | 704 | | |
| | 0 | 705 | | Services.Authorization.Dtos.UserPermissionsBundle? permissionBundle = |
| | 0 | 706 | | permissionBundleTask != null ? await permissionBundleTask : null; |
| | | 707 | | |
| | 0 | 708 | | var enrichResult = await _ordersIndexViewModelEnricher.EnrichAsync(new OrdersIndexViewModelEnrichRequest |
| | 0 | 709 | | { |
| | 0 | 710 | | ViewModel = pageViewModel, |
| | 0 | 711 | | User = user, |
| | 0 | 712 | | AccessProfile = accessProfile, |
| | 0 | 713 | | OrdersForPage = ordersForPage, |
| | 0 | 714 | | IsAdmin = isAdmin, |
| | 0 | 715 | | PrefetchedPermissionBundle = permissionBundle, |
| | 0 | 716 | | CancellationToken = HttpContext.RequestAborted |
| | 0 | 717 | | }); |
| | | 718 | | |
| | 0 | 719 | | await ApplyOrdersIndexPageViewDataAsync( |
| | 0 | 720 | | user.Id, isAdmin, HttpContext.RequestAborted, enrichResult.PermissionBundle ?? permissionBundle); |
| | 0 | 721 | | ViewBag.ReturnVisualStatusOptions = OzonStatus.ReturnVisualStatuses; |
| | | 722 | | |
| | 0 | 723 | | ViewData["LabelExistsByShipmentNumber"] = pageViewModel.LabelExistsByShipmentNumber; |
| | 0 | 724 | | ViewData["UseOrdersIndexAjax"] = true; |
| | | 725 | | |
| | 0 | 726 | | return View(pageViewModel); |
| | 0 | 727 | | } |
| | | 728 | | |
| | | 729 | | |
| | | 730 | | [HttpPost] |
| | | 731 | | public async Task<IActionResult> Index(OrderFilterModel filterData, int page = 1, string buttonState = "", |
| | | 732 | | string clearSort = "") |
| | | 733 | | |
| | | 734 | | { |
| | 0 | 735 | | filterData ??= new OrderFilterModel(); |
| | 0 | 736 | | var user = await _userCacheService.GetCachedUserAsync(User); |
| | 0 | 737 | | NormalizeSyntheticAccessProfile(user); |
| | | 738 | | |
| | 0 | 739 | | AccessProfile? accessProfile = null; |
| | | 740 | | |
| | 0 | 741 | | if (user?.AccessProfileId != null) |
| | | 742 | | |
| | | 743 | | { |
| | 0 | 744 | | accessProfile = await _accessProfileDataServices.GetAccessProfileAsync(user.AccessProfileId.Value); |
| | | 745 | | } |
| | | 746 | | |
| | | 747 | | |
| | | 748 | | // Очищаем сортировку если передан параметр clearSort |
| | | 749 | | |
| | 0 | 750 | | if (!string.IsNullOrEmpty(clearSort) && clearSort.ToLower() == "true") |
| | | 751 | | |
| | | 752 | | { |
| | 0 | 753 | | Response.Cookies.Delete("SortState"); |
| | | 754 | | |
| | 0 | 755 | | Response.Cookies.Append("SortState", OrderSortState.StandardState.ToString()); |
| | | 756 | | } |
| | | 757 | | |
| | | 758 | | |
| | | 759 | | // Проверяем, является ли пользователь админом |
| | | 760 | | |
| | 0 | 761 | | var isAdmin = User.IsInRole("Admin"); |
| | | 762 | | |
| | | 763 | | |
| | | 764 | | // Передаём информацию о том, является ли пользователь админом |
| | | 765 | | |
| | 0 | 766 | | ViewBag.IsAdmin = isAdmin; |
| | | 767 | | |
| | | 768 | | |
| | 0 | 769 | | ViewData["ButtonState"] = buttonState; |
| | | 770 | | |
| | | 771 | | |
| | | 772 | | // Проверяем наличие фильтров |
| | | 773 | | |
| | 0 | 774 | | bool hasFilters = !_dataFilterManager.AreAllPropertiesNull(filterData); |
| | | 775 | | |
| | 0 | 776 | | bool hasUserAccessRestrictions = (accessProfile != null && accessProfile.ScopeItems.Any()) |
| | 0 | 777 | | || !string.IsNullOrEmpty(_userScopeProvider.GetFilterExpression("Order")); |
| | | 778 | | |
| | | 779 | | // Определяем sortOrder для использования в DB-level сортировке |
| | 0 | 780 | | var sortOrder = GetSortStateCookie(); |
| | | 781 | | |
| | | 782 | | |
| | 0 | 783 | | int pageSize = ResolveOrdersPageSize(); |
| | | 784 | | |
| | | 785 | | // Поиск по нескольким номерам заказов — обычными страницами по MaxOrdersPageSize |
| | | 786 | | // (раньше грузили всё одной страницей pageSize=1000). |
| | 0 | 787 | | if (!string.IsNullOrWhiteSpace(filterData.ShipmentNumber) && |
| | 0 | 788 | | OrderDataFilterManager.HasMultipleShipmentNumbers(filterData.ShipmentNumber)) |
| | | 789 | | { |
| | 0 | 790 | | page = page < 1 ? 1 : page; |
| | | 791 | | } |
| | | 792 | | |
| | | 793 | | // Защита от некорректных значений page (должно быть >= 1) |
| | | 794 | | |
| | 0 | 795 | | if (page < 1) |
| | | 796 | | |
| | 0 | 797 | | page = 1; |
| | | 798 | | |
| | | 799 | | |
| | 0 | 800 | | var indexQueryResult = await LoadOrdersIndexPageAsync( |
| | 0 | 801 | | filterData, page, pageSize, sortOrder, accessProfile, hasFilters, hasUserAccessRestrictions); |
| | 0 | 802 | | var totalOrdersCount = indexQueryResult.TotalCount; |
| | | 803 | | |
| | | 804 | | |
| | | 805 | | // Формируем списки для фильтров (проверяем настройку фильтрации) |
| | | 806 | | |
| | 0 | 807 | | var filterListsByData = HttpContext.Request.Cookies["FilterListsByData"] == "true"; |
| | | 808 | | |
| | 0 | 809 | | await ApplyFilterListsToViewAsync( |
| | 0 | 810 | | filterListsByData ? indexQueryResult.Orders : null, |
| | 0 | 811 | | accessProfile, |
| | 0 | 812 | | filterListsByData); |
| | | 813 | | |
| | | 814 | | // Подрезаем dropdown-списки под DataScope-ы текущего пользователя |
| | | 815 | | |
| | | 816 | | |
| | 0 | 817 | | var serializedFilterData = JsonConvert.SerializeObject(filterData); |
| | | 818 | | |
| | 0 | 819 | | HttpContext.Response.Cookies.Append("FilterData", serializedFilterData); |
| | | 820 | | |
| | | 821 | | |
| | 0 | 822 | | SetSortOrderViewData(sortOrder); |
| | | 823 | | |
| | 0 | 824 | | var (distinctOrders, ordersForPage) = ShapeOrdersAfterLoad( |
| | 0 | 825 | | indexQueryResult.Orders, |
| | 0 | 826 | | indexQueryResult.RequiresInMemorySort, |
| | 0 | 827 | | sortOrder, |
| | 0 | 828 | | filterData, |
| | 0 | 829 | | pageSize); |
| | | 830 | | |
| | 0 | 831 | | await _ordersIndexPageDetailsService.LoadOrderDetailsForPageAsync( |
| | 0 | 832 | | ordersForPage, accessProfile, HttpContext.RequestAborted); |
| | | 833 | | |
| | | 834 | | const int viewModelPage = 1; |
| | 0 | 835 | | var pageViewModel = new OrderPageViewModel<Order, OrderFilterModel>( |
| | 0 | 836 | | distinctOrders, |
| | 0 | 837 | | viewModelPage, pageSize, filterData!, returnableCount: 0); |
| | | 838 | | |
| | 0 | 839 | | _ordersIndexPageDetailsService.ApplyDbPagination(pageViewModel, totalOrdersCount, page, pageSize); |
| | | 840 | | |
| | | 841 | | |
| | | 842 | | // Проверяем, был ли поиск по штрихкоду (EAN) и найдены ли заказы |
| | | 843 | | |
| | 0 | 844 | | if (!string.IsNullOrEmpty(filterData!.Barcode) && distinctOrders.Any()) |
| | | 845 | | |
| | | 846 | | { |
| | 0 | 847 | | TempData["SearchByBarcode"] = true; |
| | | 848 | | |
| | 0 | 849 | | TempData["BarcodeValue"] = filterData.Barcode; |
| | | 850 | | |
| | 0 | 851 | | TempData["FoundOrdersCount"] = distinctOrders.Count; |
| | | 852 | | } |
| | | 853 | | |
| | | 854 | | // Проверяем, фильтруется ли по нескольким номерам заказов |
| | 0 | 855 | | if (!string.IsNullOrWhiteSpace(filterData?.ShipmentNumber) && |
| | 0 | 856 | | OrderDataFilterManager.HasMultipleShipmentNumbers(filterData.ShipmentNumber)) |
| | | 857 | | { |
| | 0 | 858 | | var searchedNumbers = OrderDataFilterManager.GetShipmentNumbersFromFilter(filterData.ShipmentNumber); |
| | 0 | 859 | | var foundList = searchedNumbers |
| | 0 | 860 | | .Where(n => distinctOrders.Any(o => OrderDataFilterManager.ShipmentNumberMatchesSearch(o.ShipmentNum |
| | 0 | 861 | | .ToList(); |
| | 0 | 862 | | var notFoundList = searchedNumbers |
| | 0 | 863 | | .Where(n => distinctOrders.All(o => !OrderDataFilterManager.ShipmentNumberMatchesSearch(o.ShipmentNu |
| | 0 | 864 | | .ToList(); |
| | 0 | 865 | | TempData["MultipleShipmentNumberSearch"] = true; |
| | 0 | 866 | | TempData["FoundOrdersCountForShipmentNumbers"] = foundList.Count; |
| | 0 | 867 | | TempData["ShipmentNumbersFound"] = string.Join(",", foundList); |
| | 0 | 868 | | TempData["ShipmentNumbersSearchedCount"] = searchedNumbers.Count; |
| | 0 | 869 | | if (notFoundList.Count > 0) |
| | 0 | 870 | | TempData["ShipmentNumbersNotFound"] = string.Join(",", notFoundList); |
| | | 871 | | } |
| | | 872 | | |
| | | 873 | | |
| | 0 | 874 | | await _ordersIndexPageDetailsService.PopulateUniqueCountsAsync( |
| | 0 | 875 | | pageViewModel, distinctOrders, filterData!.IncludeArchived, HttpContext.RequestAborted); |
| | | 876 | | |
| | 0 | 877 | | if (user == null) |
| | | 878 | | |
| | | 879 | | { |
| | 0 | 880 | | return Redirect("/Identity/Account/Login"); |
| | | 881 | | } |
| | | 882 | | |
| | 0 | 883 | | pageViewModel.User = user; |
| | | 884 | | |
| | 0 | 885 | | if (!string.IsNullOrWhiteSpace(filterData?.ShipmentNumber) && |
| | 0 | 886 | | OrderDataFilterManager.HasMultipleShipmentNumbers(filterData.ShipmentNumber)) |
| | | 887 | | { |
| | 0 | 888 | | await _ordersIndexViewModelEnricher.EnrichAsync(new OrdersIndexViewModelEnrichRequest |
| | 0 | 889 | | { |
| | 0 | 890 | | ViewModel = pageViewModel, |
| | 0 | 891 | | User = user, |
| | 0 | 892 | | AccessProfile = accessProfile, |
| | 0 | 893 | | OrdersForPage = ordersForPage, |
| | 0 | 894 | | IsAdmin = isAdmin, |
| | 0 | 895 | | LoadFieldReadAccess = false, |
| | 0 | 896 | | CancellationToken = HttpContext.RequestAborted |
| | 0 | 897 | | }); |
| | 0 | 898 | | ViewData["LabelExistsByShipmentNumber"] = pageViewModel.LabelExistsByShipmentNumber; |
| | 0 | 899 | | await ApplyOrdersIndexPageViewDataAsync(user.Id, isAdmin, HttpContext.RequestAborted); |
| | 0 | 900 | | return View("~/Areas/Studio2/Views/Orders/Index.cshtml", pageViewModel); |
| | | 901 | | } |
| | | 902 | | |
| | | 903 | | |
| | | 904 | | // Используем POST-Redirect-GET паттерн для предотвращения предупреждения о повторной отправке формы |
| | | 905 | | |
| | 0 | 906 | | return RedirectToAction(nameof(Index), new { page = page }); |
| | 0 | 907 | | } |
| | | 908 | | |
| | | 909 | | |
| | | 910 | | public async Task<IActionResult> ViewOrders(int[] ids) |
| | | 911 | | { |
| | 0 | 912 | | List<Order> ordereToView = []; |
| | 0 | 913 | | ids = await FilterOrderIdsByDataScopeAsync(ids); |
| | | 914 | | |
| | 0 | 915 | | var returnableCount = 0; // не используется в UI; COUNT по всей таблице убран для скорости Index |
| | | 916 | | |
| | 0 | 917 | | SetInfoMessage(); |
| | | 918 | | |
| | | 919 | | |
| | 0 | 920 | | var user = await _userCacheService.GetCachedUserAsync(User); |
| | | 921 | | |
| | 0 | 922 | | var isAdmin = User.IsInRole("Admin"); |
| | | 923 | | |
| | 0 | 924 | | ViewBag.IsAdmin = isAdmin; |
| | | 925 | | |
| | 0 | 926 | | AccessProfile? accessProfile = null; |
| | | 927 | | |
| | 0 | 928 | | if (user?.AccessProfileId != null) |
| | | 929 | | |
| | | 930 | | { |
| | 0 | 931 | | accessProfile = await _accessProfileDataServices.GetAccessProfileAsync(user.AccessProfileId.Value); |
| | | 932 | | } |
| | | 933 | | |
| | | 934 | | |
| | 0 | 935 | | var orders = await _orderServices.GetOrdersNoTracking(ids); |
| | 0 | 936 | | ordereToView.AddRange(orders); |
| | | 937 | | |
| | | 938 | | |
| | 0 | 939 | | string? filterDataString = HttpContext.Request.Cookies["FilterData"]; |
| | | 940 | | |
| | 0 | 941 | | var filterData = new OrderFilterModel(); |
| | | 942 | | |
| | 0 | 943 | | if (!string.IsNullOrEmpty(filterDataString)) |
| | | 944 | | |
| | | 945 | | { |
| | 0 | 946 | | filterData = JsonConvert.DeserializeObject<OrderFilterModel>(filterDataString) ?? new OrderFilterModel() |
| | | 947 | | } |
| | | 948 | | |
| | | 949 | | |
| | 0 | 950 | | var pageViewModel = new OrderPageViewModel<Order, OrderFilterModel>(ordereToView, 1, ordereToView.Count(), |
| | 0 | 951 | | filterData, returnableCount) |
| | 0 | 952 | | |
| | 0 | 953 | | { |
| | 0 | 954 | | UniqueArticles = await _orderServices.GetArticleCountsForOrdersAsync(ordereToView, filterData.IncludeArc |
| | 0 | 955 | | |
| | 0 | 956 | | UniqueDeliveryCitys = await _orderServices.GetDeliveryCityCountsForOrdersAsync(ordereToView, filterData. |
| | 0 | 957 | | |
| | 0 | 958 | | UniqueNumbers = await _orderServices.GetShipmentBaseCountsForOrdersAsync(ordereToView, filterData.Includ |
| | 0 | 959 | | }; |
| | | 960 | | |
| | 0 | 961 | | if (user == null) |
| | | 962 | | { |
| | 0 | 963 | | return Redirect("/Identity/Account/Login"); |
| | | 964 | | } |
| | | 965 | | |
| | 0 | 966 | | pageViewModel.User = user; |
| | | 967 | | |
| | 0 | 968 | | if (user != null) |
| | | 969 | | { |
| | 0 | 970 | | pageViewModel.OrderListFieldReadAccess = await BuildOrderListFieldReadMapAsync(user.Id, HttpContext.Requ |
| | | 971 | | } |
| | | 972 | | |
| | 0 | 973 | | if (pageViewModel.User != null && pageViewModel.User.AccessProfileId != null) |
| | | 974 | | |
| | | 975 | | { |
| | 0 | 976 | | pageViewModel.User.AccessProfile = accessProfile ?? await _context.AccessProfiles.FindAsync(pageViewMode |
| | | 977 | | } |
| | | 978 | | |
| | | 979 | | |
| | | 980 | | |
| | | 981 | | // Формируем списки для фильтров (проверяем настройку фильтрации) |
| | | 982 | | |
| | 0 | 983 | | var filterListsByData = HttpContext.Request.Cookies["FilterListsByData"] == "true"; |
| | | 984 | | |
| | 0 | 985 | | await ApplyFilterListsToViewAsync( |
| | 0 | 986 | | filterListsByData ? ordereToView : null, |
| | 0 | 987 | | accessProfile, |
| | 0 | 988 | | filterListsByData); |
| | | 989 | | |
| | | 990 | | // Подрезаем dropdown-списки под DataScope-ы текущего пользователя |
| | | 991 | | |
| | | 992 | | |
| | 0 | 993 | | await ApplyOrdersIndexPageViewDataAsync(user!.Id, isAdmin, HttpContext.RequestAborted); |
| | | 994 | | |
| | 0 | 995 | | return View("~/Areas/Studio2/Views/Orders/Index.cshtml", pageViewModel); |
| | 0 | 996 | | } |
| | | 997 | | |
| | | 998 | | |
| | | 999 | | |
| | | 1000 | | [HttpPost] |
| | | 1001 | | public async Task<IActionResult> DelSortStateCookie() |
| | | 1002 | | |
| | | 1003 | | { |
| | 0 | 1004 | | await Task.CompletedTask; |
| | 0 | 1005 | | Response.Cookies.Delete("SortState"); |
| | | 1006 | | |
| | 0 | 1007 | | Response.Cookies.Append("SortState", OrderSortState.StandardState.ToString()); |
| | | 1008 | | |
| | 0 | 1009 | | return RedirectToAction(nameof(System.Index)); |
| | 0 | 1010 | | } |
| | | 1011 | | |
| | | 1012 | | |
| | | 1013 | | public async Task<IActionResult> DelSortStateCookieForV2() |
| | | 1014 | | |
| | | 1015 | | { |
| | 0 | 1016 | | await Task.CompletedTask; |
| | 0 | 1017 | | Response.Cookies.Delete("SortState"); |
| | | 1018 | | |
| | 0 | 1019 | | Response.Cookies.Append("SortState", OrderSortState.StandardState.ToString()); |
| | | 1020 | | |
| | 0 | 1021 | | return RedirectToAction(nameof(Index)); |
| | 0 | 1022 | | } |
| | | 1023 | | |
| | | 1024 | | |
| | | 1025 | | [HttpPost] |
| | | 1026 | | public async Task<IActionResult> SetPageSize(int size) |
| | | 1027 | | |
| | | 1028 | | { |
| | 0 | 1029 | | await Task.CompletedTask; |
| | 0 | 1030 | | size = Math.Clamp(size, 1, MaxOrdersPageSize); |
| | | 1031 | | |
| | 0 | 1032 | | Response.Cookies.Append("PageSize", size.ToString()); |
| | | 1033 | | |
| | 0 | 1034 | | return RedirectToAction(nameof(System.Index)); |
| | 0 | 1035 | | } |
| | | 1036 | | |
| | | 1037 | | |
| | | 1038 | | [HttpPost] |
| | | 1039 | | public async Task<IActionResult> SetPageSizeForV2(int size) |
| | | 1040 | | |
| | | 1041 | | { |
| | 0 | 1042 | | await Task.CompletedTask; |
| | 0 | 1043 | | size = Math.Clamp(size, 1, MaxOrdersPageSize); |
| | | 1044 | | |
| | 0 | 1045 | | Response.Cookies.Append("PageSize", size.ToString()); |
| | | 1046 | | |
| | 0 | 1047 | | return RedirectToAction(nameof(Index)); |
| | 0 | 1048 | | } |
| | | 1049 | | |
| | | 1050 | | |
| | | 1051 | | public async Task<IActionResult> Update() |
| | | 1052 | | |
| | | 1053 | | { |
| | 0 | 1054 | | await _cacheUpdater.Update(_cache); |
| | | 1055 | | |
| | 0 | 1056 | | return RedirectToAction(nameof(System.Index)); |
| | 0 | 1057 | | } |
| | | 1058 | | |
| | | 1059 | | |
| | | 1060 | | public async Task<IActionResult> UpdateV2() |
| | | 1061 | | |
| | | 1062 | | { |
| | 0 | 1063 | | await _cacheUpdater.Update(_cache); |
| | | 1064 | | |
| | 0 | 1065 | | return RedirectToAction(nameof(Index)); |
| | 0 | 1066 | | } |
| | | 1067 | | |
| | | 1068 | | |
| | | 1069 | | |
| | | 1070 | | |
| | | 1071 | | |
| | | 1072 | | |
| | | 1073 | | public async Task<IActionResult> Delete(int id, int page) |
| | | 1074 | | |
| | | 1075 | | { |
| | | 1076 | | try |
| | | 1077 | | |
| | | 1078 | | { |
| | 0 | 1079 | | int result = await _orderServices.DeleteOrder(id); |
| | | 1080 | | |
| | | 1081 | | |
| | 0 | 1082 | | if (result == 0) |
| | | 1083 | | |
| | | 1084 | | { |
| | 0 | 1085 | | TempData["ErorrResult"] = $"Для удаления доступны только заказы со статусом '<b>Не указан</b>'."; |
| | | 1086 | | } |
| | | 1087 | | |
| | 0 | 1088 | | else if (result == 1) |
| | | 1089 | | |
| | | 1090 | | { |
| | 0 | 1091 | | await _cache.RemoveOrderFromCache(id); |
| | | 1092 | | |
| | 0 | 1093 | | ClearSelectedIdsSession(); |
| | | 1094 | | |
| | 0 | 1095 | | await NotificationService.NotifyAllAsync($"Заказаid={id} успешно удален."); |
| | | 1096 | | |
| | 0 | 1097 | | TempData["TransactionResult"] = $"Заказ успешно удален."; |
| | | 1098 | | } |
| | | 1099 | | |
| | | 1100 | | else |
| | | 1101 | | |
| | | 1102 | | { |
| | 0 | 1103 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | | 1104 | | } |
| | 0 | 1105 | | } |
| | | 1106 | | |
| | 0 | 1107 | | catch |
| | | 1108 | | |
| | | 1109 | | { |
| | 0 | 1110 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | 0 | 1111 | | } |
| | | 1112 | | |
| | | 1113 | | |
| | 0 | 1114 | | return RedirectToAction(nameof(System.Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | 0 | 1115 | | } |
| | | 1116 | | |
| | | 1117 | | |
| | | 1118 | | public async Task<IActionResult> DeleteV2(int id, int page) |
| | | 1119 | | |
| | | 1120 | | { |
| | | 1121 | | try |
| | | 1122 | | |
| | | 1123 | | { |
| | 0 | 1124 | | int result = await _orderServices.DeleteOrder(id); |
| | | 1125 | | |
| | | 1126 | | |
| | 0 | 1127 | | if (result == 0) |
| | | 1128 | | |
| | | 1129 | | { |
| | 0 | 1130 | | TempData["ErorrResult"] = $"Для удаления доступны только заказы со статусом '<b>Не указан</b>'."; |
| | | 1131 | | } |
| | | 1132 | | |
| | 0 | 1133 | | else if (result == 1) |
| | | 1134 | | |
| | | 1135 | | { |
| | 0 | 1136 | | await _cache.RemoveOrderFromCache(id); |
| | | 1137 | | |
| | 0 | 1138 | | ClearSelectedIdsSession(); |
| | | 1139 | | |
| | 0 | 1140 | | await NotificationService.NotifyAllAsync($"Заказ id={id} успешно удален."); |
| | | 1141 | | |
| | 0 | 1142 | | TempData["TransactionResult"] = $"Заказ успешно удален."; |
| | | 1143 | | } |
| | | 1144 | | |
| | | 1145 | | else |
| | | 1146 | | |
| | | 1147 | | { |
| | 0 | 1148 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | | 1149 | | } |
| | 0 | 1150 | | } |
| | | 1151 | | |
| | 0 | 1152 | | catch |
| | | 1153 | | |
| | | 1154 | | { |
| | 0 | 1155 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | 0 | 1156 | | } |
| | | 1157 | | |
| | | 1158 | | |
| | 0 | 1159 | | return RedirectToAction(nameof(Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | 0 | 1160 | | } |
| | | 1161 | | |
| | | 1162 | | /// <summary> |
| | | 1163 | | /// Преобразует техническое сообщение об ошибке Ozon API в понятное для пользователя. |
| | | 1164 | | /// </summary> |
| | | 1165 | | private static string GetFriendlySplitErrorMessage(Exception ex) |
| | | 1166 | | { |
| | 0 | 1167 | | var msg = ex.Message; |
| | 0 | 1168 | | if (msg.Contains("invalid status", StringComparison.OrdinalIgnoreCase) || |
| | 0 | 1169 | | msg.Contains("expected status 300", StringComparison.OrdinalIgnoreCase)) |
| | | 1170 | | { |
| | 0 | 1171 | | return "Разделение на Ozon недоступно: отправление в неподходящем статусе. Разделять можно только заказы |
| | | 1172 | | } |
| | 0 | 1173 | | if (msg.Contains("not all exemplars", StringComparison.OrdinalIgnoreCase)) |
| | | 1174 | | { |
| | 0 | 1175 | | return "Разделение на Ozon недоступно: отправление содержит другие товары или количество не совпадает с |
| | | 1176 | | } |
| | 0 | 1177 | | if (msg.Contains("not enough in parent posting", StringComparison.OrdinalIgnoreCase)) |
| | | 1178 | | { |
| | 0 | 1179 | | return "Разделение на Ozon недоступно: в отправлении недостаточно товара для указанного разделения. Коли |
| | | 1180 | | } |
| | 0 | 1181 | | if (msg.Contains("Ozon API вернул пустые номера", StringComparison.OrdinalIgnoreCase)) |
| | | 1182 | | { |
| | 0 | 1183 | | return msg; |
| | | 1184 | | } |
| | 0 | 1185 | | return "Ошибка при разделении заказа: " + msg; |
| | | 1186 | | } |
| | | 1187 | | |
| | | 1188 | | /// <summary> |
| | | 1189 | | /// Выполняет разделение заказа с вызовом Ozon API для заказов Ozon-клиентов (quantity > 1). |
| | | 1190 | | /// Перед разделением проверяет количество в Ozon через /v3/posting/fbs/get. |
| | | 1191 | | /// Если в Ozon достаточно — разделяет на Ozon. Если меньше — разделяет локально до уровня Ozon с пропорцией. |
| | | 1192 | | /// При onlyInSystem=true Ozon API не вызывается, разделение только в системе. |
| | | 1193 | | /// </summary> |
| | | 1194 | | /// <returns>Новый заказ, флаги разделения и сведения о частях для пайплайна этикеток.</returns> |
| | | 1195 | | private async Task<(Order newOrder, bool wasOzonSplit, bool wasOzonQuantityAdjusted, SplitOrderPartsResult parts |
| | | 1196 | | { |
| | 0 | 1197 | | var order = await _context.Orders |
| | 0 | 1198 | | .Include(o => o.ProductInfo) |
| | 0 | 1199 | | .Include(o => o.OzonClient) |
| | 0 | 1200 | | .FirstOrDefaultAsync(o => o.Id == orderId); |
| | | 1201 | | |
| | 0 | 1202 | | if (order == null) |
| | 0 | 1203 | | throw new InvalidOperationException($"Заказ {orderId} не найден"); |
| | | 1204 | | |
| | 0 | 1205 | | (string posting1, string posting2)? ozonPostingNumbers = null; |
| | 0 | 1206 | | var wasOzonSplit = false; |
| | 0 | 1207 | | var wasOzonQuantityAdjusted = false; |
| | 0 | 1208 | | var actualPart1 = part1; |
| | 0 | 1209 | | var actualPart2 = part2; |
| | 0 | 1210 | | int? totalQuantityOverride = null; |
| | | 1211 | | |
| | 0 | 1212 | | if (!onlyInSystem && order.OzonClientId != null |
| | 0 | 1213 | | && order.Quantity > 1 |
| | 0 | 1214 | | && !string.IsNullOrEmpty(order.ShipmentNumber)) |
| | | 1215 | | { |
| | 0 | 1216 | | var ozonClient = await _ozonClientServices.GetOzonClientAsync(order.OzonClientId.Value); |
| | 0 | 1217 | | if (ozonClient != null |
| | 0 | 1218 | | && !string.IsNullOrWhiteSpace(ozonClient.DecryptClientId) |
| | 0 | 1219 | | && !string.IsNullOrWhiteSpace(ozonClient.DecryptApiKey)) |
| | | 1220 | | { |
| | 0 | 1221 | | _ozonApiDataManager.SetClient(ozonClient.DecryptClientId, ozonClient.DecryptApiKey); |
| | | 1222 | | |
| | 0 | 1223 | | var postingNumber = OzonPostingNumberHelper.GetOzonApiPostingNumber(order.ShipmentNumber); |
| | | 1224 | | |
| | 0 | 1225 | | var productId = long.Parse(order.ProductInfo!.FbsOzonSkuId!); |
| | 0 | 1226 | | var ozonQuantity = await _ozonApiDataManager.GetPostingProductQuantityAsync(postingNumber, productId |
| | 0 | 1227 | | var ozonSku = await _ozonApiDataManager.GetPostingProductSkuAsync(postingNumber, productId) |
| | 0 | 1228 | | ?? throw new InvalidOperationException("Ozon API не вернул SKU товара для разделения отправления |
| | | 1229 | | |
| | 0 | 1230 | | if (ozonQuantity > 0 && ozonQuantity < part1 + part2) |
| | | 1231 | | { |
| | 0 | 1232 | | wasOzonQuantityAdjusted = true; |
| | 0 | 1233 | | if (ozonQuantity < 2) |
| | | 1234 | | { |
| | 0 | 1235 | | actualPart1 = part1; |
| | 0 | 1236 | | actualPart2 = part2; |
| | | 1237 | | } |
| | | 1238 | | else |
| | | 1239 | | { |
| | 0 | 1240 | | var total = part1 + part2; |
| | 0 | 1241 | | actualPart1 = (int)Math.Round(ozonQuantity * (double)part1 / total); |
| | 0 | 1242 | | if (actualPart1 < 1) actualPart1 = 1; |
| | 0 | 1243 | | actualPart2 = ozonQuantity - actualPart1; |
| | 0 | 1244 | | if (actualPart2 < 1) |
| | | 1245 | | { |
| | 0 | 1246 | | actualPart2 = 1; |
| | 0 | 1247 | | actualPart1 = ozonQuantity - 1; |
| | | 1248 | | } |
| | 0 | 1249 | | totalQuantityOverride = ozonQuantity; |
| | | 1250 | | } |
| | | 1251 | | } |
| | 0 | 1252 | | else if (ozonQuantity >= part1 + part2) |
| | | 1253 | | { |
| | 0 | 1254 | | var postings = new List<FbsSplitPosting> |
| | 0 | 1255 | | { |
| | 0 | 1256 | | new FbsSplitPosting |
| | 0 | 1257 | | { |
| | 0 | 1258 | | Products = new List<FbsSplitProduct> |
| | 0 | 1259 | | { |
| | 0 | 1260 | | new FbsSplitProduct { ProductId = ozonSku, Quantity = part1 } |
| | 0 | 1261 | | } |
| | 0 | 1262 | | }, |
| | 0 | 1263 | | new FbsSplitPosting |
| | 0 | 1264 | | { |
| | 0 | 1265 | | Products = new List<FbsSplitProduct> |
| | 0 | 1266 | | { |
| | 0 | 1267 | | new FbsSplitProduct { ProductId = ozonSku, Quantity = part2 } |
| | 0 | 1268 | | } |
| | 0 | 1269 | | } |
| | 0 | 1270 | | }; |
| | | 1271 | | |
| | 0 | 1272 | | var result = await _ozonApiDataManager.SplitFbsPosting(postingNumber, postings); |
| | 0 | 1273 | | var mapped = OzonSplitPostingMapper.Map(result, part1, part2); |
| | 0 | 1274 | | ozonPostingNumbers = mapped; |
| | 0 | 1275 | | wasOzonSplit = true; |
| | | 1276 | | } |
| | 0 | 1277 | | else if (ozonQuantity == 0) |
| | | 1278 | | { |
| | 0 | 1279 | | throw new InvalidOperationException("Товар не найден в отправлении Ozon или ошибка при получении |
| | | 1280 | | } |
| | 0 | 1281 | | } |
| | | 1282 | | } |
| | | 1283 | | |
| | 0 | 1284 | | var newOrder = await _orderServices.SplitOrder(orderId, actualPart1, actualPart2, ozonPostingNumbers, totalQ |
| | 0 | 1285 | | if (newOrder == null) |
| | | 1286 | | { |
| | 0 | 1287 | | throw new InvalidOperationException($"Не удалось разделить заказ {orderId}"); |
| | | 1288 | | } |
| | | 1289 | | |
| | 0 | 1290 | | var originalAfterSplit = await _context.Orders.AsNoTracking() |
| | 0 | 1291 | | .FirstOrDefaultAsync(o => o.Id == orderId); |
| | 0 | 1292 | | if (originalAfterSplit == null) |
| | | 1293 | | { |
| | 0 | 1294 | | throw new InvalidOperationException($"Заказ {orderId} не найден после разделения."); |
| | | 1295 | | } |
| | | 1296 | | |
| | 0 | 1297 | | var parts = new SplitOrderPartsResult |
| | 0 | 1298 | | { |
| | 0 | 1299 | | OriginalOrderId = orderId, |
| | 0 | 1300 | | NewOrderId = newOrder.Id, |
| | 0 | 1301 | | ShipmentNumbers = new[] |
| | 0 | 1302 | | { |
| | 0 | 1303 | | originalAfterSplit.ShipmentNumber ?? string.Empty, |
| | 0 | 1304 | | newOrder.ShipmentNumber ?? string.Empty |
| | 0 | 1305 | | }, |
| | 0 | 1306 | | IsOzonSplit = wasOzonSplit |
| | 0 | 1307 | | }; |
| | | 1308 | | |
| | 0 | 1309 | | return (newOrder, wasOzonSplit, wasOzonQuantityAdjusted, parts); |
| | 0 | 1310 | | } |
| | | 1311 | | |
| | | 1312 | | public async Task<IActionResult> SplitOrder(string ids, int page, string splitOption, bool onlyInSystem = false) |
| | | 1313 | | |
| | | 1314 | | { |
| | | 1315 | | try |
| | | 1316 | | { |
| | 0 | 1317 | | int[] idArray = ids.Split(',').Select(int.Parse).ToArray(); |
| | | 1318 | | |
| | 0 | 1319 | | var parts = splitOption.Split(' ').Select(int.Parse).ToArray(); |
| | | 1320 | | |
| | 0 | 1321 | | var anyOzonSplit = false; |
| | 0 | 1322 | | var anyOzonQuantityAdjusted = false; |
| | 0 | 1323 | | foreach (var id in idArray) |
| | | 1324 | | |
| | | 1325 | | { |
| | 0 | 1326 | | var (_, wasOzonSplit, wasOzonQuantityAdjusted, _) = |
| | 0 | 1327 | | await PerformSplitOrderAsync(id, parts[0], parts[1], onlyInSystem); |
| | 0 | 1328 | | anyOzonSplit = anyOzonSplit || wasOzonSplit; |
| | 0 | 1329 | | anyOzonQuantityAdjusted = anyOzonQuantityAdjusted || wasOzonQuantityAdjusted; |
| | | 1330 | | } |
| | | 1331 | | |
| | | 1332 | | |
| | 0 | 1333 | | await _cache.Update(); |
| | | 1334 | | |
| | 0 | 1335 | | if (anyOzonSplit) |
| | | 1336 | | { |
| | 0 | 1337 | | TempData["TransactionResult"] = "Заказ успешно разделен на Ozon. Номера отправлений обновлены из отв |
| | | 1338 | | } |
| | 0 | 1339 | | else if (anyOzonQuantityAdjusted) |
| | | 1340 | | { |
| | 0 | 1341 | | TempData["TransactionResult"] = "Заказ разделен локально: количество приведено к данным Ozon (в Ozon |
| | | 1342 | | } |
| | | 1343 | | else |
| | | 1344 | | { |
| | 0 | 1345 | | TempData["TransactionResult"] = "Заказ успешно разделен."; |
| | | 1346 | | } |
| | | 1347 | | |
| | 0 | 1348 | | return RedirectToAction(nameof(Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | | 1349 | | } |
| | 0 | 1350 | | catch (Exception ex) |
| | | 1351 | | { |
| | 0 | 1352 | | TempData["ErorrResult"] = GetFriendlySplitErrorMessage(ex); |
| | 0 | 1353 | | return RedirectToAction(nameof(Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | | 1354 | | } |
| | 0 | 1355 | | } |
| | | 1356 | | |
| | | 1357 | | |
| | | 1358 | | [HttpPost] |
| | | 1359 | | |
| | | 1360 | | |
| | | 1361 | | public async Task<IActionResult> MultiplayDeleteOrders(string ids, int page) |
| | | 1362 | | |
| | | 1363 | | { |
| | 0 | 1364 | | if (ids == null) |
| | | 1365 | | |
| | | 1366 | | { |
| | 0 | 1367 | | TempData["ErorrResult"] = |
| | 0 | 1368 | | $"Не удалось удалить выбранные заказы.<br>Было передано слишком большое количество записей."; |
| | | 1369 | | |
| | 0 | 1370 | | return RedirectToAction("Index"); |
| | | 1371 | | } |
| | | 1372 | | |
| | | 1373 | | |
| | 0 | 1374 | | int[] idArray = ids.Split(',').Select(int.Parse).ToArray(); |
| | | 1375 | | |
| | | 1376 | | |
| | | 1377 | | try |
| | | 1378 | | |
| | | 1379 | | { |
| | 0 | 1380 | | int result = await _orderServices.MultiplayDeleteOrders(idArray); |
| | | 1381 | | |
| | | 1382 | | |
| | 0 | 1383 | | if (result == 0) |
| | | 1384 | | |
| | | 1385 | | { |
| | 0 | 1386 | | TempData["ErorrResult"] = $"Для удаления доступны только заказы со статусом '<b>Не указан</b>'."; |
| | | 1387 | | } |
| | | 1388 | | |
| | 0 | 1389 | | else if (result > 0) |
| | | 1390 | | |
| | | 1391 | | { |
| | 0 | 1392 | | await _cache.RemoveOrdersFromCache(idArray); |
| | | 1393 | | |
| | 0 | 1394 | | ClearSelectedIdsSession(); |
| | | 1395 | | |
| | 0 | 1396 | | await NotificationService.NotifyAllAsync($"Удалено <b>{result}</b> заказов."); |
| | | 1397 | | |
| | 0 | 1398 | | TempData["TransactionResult"] = $"Удалено <b>{result}</b> заказов."; |
| | | 1399 | | } |
| | | 1400 | | |
| | | 1401 | | else |
| | | 1402 | | |
| | | 1403 | | { |
| | 0 | 1404 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | | 1405 | | } |
| | 0 | 1406 | | } |
| | | 1407 | | |
| | 0 | 1408 | | catch |
| | | 1409 | | |
| | | 1410 | | { |
| | 0 | 1411 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | 0 | 1412 | | } |
| | | 1413 | | |
| | | 1414 | | |
| | 0 | 1415 | | return RedirectToAction(nameof(System.Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | 0 | 1416 | | } |
| | | 1417 | | |
| | | 1418 | | |
| | | 1419 | | public async Task<IActionResult> DeleteOrderPage(List<int> ordersIdsToDelete) |
| | | 1420 | | |
| | | 1421 | | { |
| | 0 | 1422 | | var ordersToDelete = ordersIdsToDelete != null && ordersIdsToDelete.Any() |
| | 0 | 1423 | | ? await _orderServices.GetOrdersNoTracking(ordersIdsToDelete.ToArray()) |
| | 0 | 1424 | | : new List<Order>(); |
| | | 1425 | | |
| | | 1426 | | |
| | 0 | 1427 | | return View(new DeleteOrderViewModel() |
| | 0 | 1428 | | |
| | 0 | 1429 | | { IdsToDelete = ordersIdsToDelete ?? [], OrdersToDelete = ordersToDelete }); |
| | 0 | 1430 | | } |
| | | 1431 | | |
| | | 1432 | | |
| | | 1433 | | public async Task<IActionResult> MultiplayDeleteOrdersV2(string ids, int page) |
| | | 1434 | | |
| | | 1435 | | { |
| | 0 | 1436 | | if (ids == null) |
| | | 1437 | | |
| | | 1438 | | { |
| | 0 | 1439 | | TempData["ErorrResult"] = |
| | 0 | 1440 | | $"Не удалось удалить выбранные заказы.<br>Было передано слишком большое количество записей."; |
| | | 1441 | | |
| | 0 | 1442 | | return RedirectToAction("Index"); |
| | | 1443 | | } |
| | | 1444 | | |
| | | 1445 | | |
| | 0 | 1446 | | int[] idArray = ids.Split(',').Select(int.Parse).ToArray(); |
| | | 1447 | | |
| | | 1448 | | |
| | | 1449 | | try |
| | | 1450 | | |
| | | 1451 | | { |
| | 0 | 1452 | | int result = await _orderServices.MultiplayDeleteOrders(idArray); |
| | | 1453 | | |
| | | 1454 | | |
| | 0 | 1455 | | if (result == 0) |
| | | 1456 | | |
| | | 1457 | | { |
| | 0 | 1458 | | TempData["ErorrResult"] = $"Для удаления доступны только заказы со статусом '<b>Не указан</b>'."; |
| | | 1459 | | } |
| | | 1460 | | |
| | 0 | 1461 | | else if (result > 0) |
| | | 1462 | | |
| | | 1463 | | { |
| | 0 | 1464 | | await _cache.RemoveOrdersFromCache(idArray); |
| | | 1465 | | |
| | 0 | 1466 | | ClearSelectedIdsSession(); |
| | | 1467 | | |
| | 0 | 1468 | | await NotificationService.NotifyAllAsync($"Удалено <b>{result}</b> заказов."); |
| | | 1469 | | |
| | 0 | 1470 | | TempData["TransactionResult"] = $"Удалено <b>{result}</b> заказов."; |
| | | 1471 | | } |
| | | 1472 | | |
| | | 1473 | | else |
| | | 1474 | | |
| | | 1475 | | { |
| | 0 | 1476 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | | 1477 | | } |
| | 0 | 1478 | | } |
| | | 1479 | | |
| | 0 | 1480 | | catch |
| | | 1481 | | |
| | | 1482 | | { |
| | 0 | 1483 | | TempData["ErorrResult"] = $"Ошибка при удалении заказа."; |
| | 0 | 1484 | | } |
| | | 1485 | | |
| | | 1486 | | |
| | 0 | 1487 | | return RedirectToAction(nameof(Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | 0 | 1488 | | } |
| | | 1489 | | |
| | | 1490 | | |
| | | 1491 | | public async Task<IActionResult> CancellationOrders(string ids, int page) |
| | | 1492 | | |
| | | 1493 | | { |
| | 0 | 1494 | | if (ids == null) |
| | | 1495 | | |
| | | 1496 | | { |
| | 0 | 1497 | | TempData["ErorrResult"] = |
| | 0 | 1498 | | $"Не удалось изменить выбранные заказы.<br>Было передано слишком большое количество записей."; |
| | | 1499 | | |
| | 0 | 1500 | | return RedirectToAction("Index"); |
| | | 1501 | | } |
| | | 1502 | | |
| | | 1503 | | |
| | 0 | 1504 | | int[] idArray = ids.Split(',').Select(int.Parse).ToArray(); |
| | | 1505 | | |
| | | 1506 | | |
| | | 1507 | | try |
| | | 1508 | | |
| | | 1509 | | { |
| | 0 | 1510 | | int result = await _orderServices.CancellationOrders(idArray); |
| | | 1511 | | |
| | | 1512 | | |
| | 0 | 1513 | | if (result == 0) |
| | | 1514 | | |
| | | 1515 | | { |
| | 0 | 1516 | | TempData["ErorrResult"] = $"Для изменения доступны только заказы со статусом '<b>Не указан</b>'."; |
| | | 1517 | | } |
| | | 1518 | | |
| | 0 | 1519 | | else if (result > 0) |
| | | 1520 | | |
| | | 1521 | | { |
| | 0 | 1522 | | await _cache.RemoveOrdersFromCache(idArray); |
| | | 1523 | | |
| | 0 | 1524 | | ClearSelectedIdsSession(); |
| | | 1525 | | |
| | 0 | 1526 | | await NotificationService.NotifyAllAsync($"Изменено <b>{result}</b> заказов."); |
| | | 1527 | | |
| | 0 | 1528 | | TempData["TransactionResult"] = $"Изменено <b>{result}</b> заказов."; |
| | | 1529 | | } |
| | | 1530 | | |
| | | 1531 | | else |
| | | 1532 | | |
| | | 1533 | | { |
| | 0 | 1534 | | TempData["ErorrResult"] = $"Ошибка при изменении заказа."; |
| | | 1535 | | } |
| | 0 | 1536 | | } |
| | | 1537 | | |
| | 0 | 1538 | | catch |
| | | 1539 | | |
| | | 1540 | | { |
| | 0 | 1541 | | TempData["ErorrResult"] = $"Ошибка при изменении заказа."; |
| | 0 | 1542 | | } |
| | | 1543 | | |
| | | 1544 | | |
| | 0 | 1545 | | return RedirectToAction(nameof(Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | 0 | 1546 | | } |
| | | 1547 | | |
| | | 1548 | | |
| | | 1549 | | [HttpPost] |
| | | 1550 | | public async Task<IActionResult> Recover(int id, DateTime start, DateTime end) |
| | | 1551 | | |
| | | 1552 | | { |
| | 0 | 1553 | | await _cache.UpdateCacheIncrementally(id); |
| | | 1554 | | |
| | 0 | 1555 | | ClearSelectedIdsSession(); |
| | | 1556 | | |
| | 0 | 1557 | | return RedirectToAction("Index"); |
| | 0 | 1558 | | } |
| | | 1559 | | |
| | | 1560 | | |
| | | 1561 | | public async Task<IActionResult> ConfirmAccepted(int id, string ids, int page) |
| | | 1562 | | |
| | | 1563 | | { |
| | 0 | 1564 | | if (ids == null || ids.Length == 0) |
| | | 1565 | | |
| | | 1566 | | { |
| | 0 | 1567 | | await _orderServices.ConfirmAccepted(id); |
| | | 1568 | | |
| | 0 | 1569 | | await _cache.UpdateCacheIncrementally(id); |
| | | 1570 | | } |
| | | 1571 | | |
| | | 1572 | | else |
| | | 1573 | | |
| | | 1574 | | { |
| | 0 | 1575 | | int[] idArray = ids.Split(',').Select(int.Parse).ToArray(); |
| | | 1576 | | |
| | 0 | 1577 | | foreach (var concretId in idArray) |
| | | 1578 | | |
| | | 1579 | | { |
| | 0 | 1580 | | await _orderServices.ConfirmAccepted(concretId); |
| | | 1581 | | |
| | 0 | 1582 | | await _cache.UpdateCacheIncrementally(concretId); |
| | | 1583 | | } |
| | | 1584 | | |
| | | 1585 | | |
| | 0 | 1586 | | if (Request.Cookies["selectedIds"] != null) |
| | | 1587 | | |
| | | 1588 | | { |
| | 0 | 1589 | | Response.Cookies.Delete("selectedIds"); |
| | | 1590 | | } |
| | | 1591 | | } |
| | | 1592 | | |
| | | 1593 | | |
| | 0 | 1594 | | return RedirectToAction(nameof(System.Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | 0 | 1595 | | } |
| | | 1596 | | |
| | | 1597 | | |
| | | 1598 | | public async Task<IActionResult> ConfirmAcceptedV2(int id, string ids, int page) |
| | | 1599 | | |
| | | 1600 | | { |
| | 0 | 1601 | | if (ids == null || ids.Length == 0) |
| | | 1602 | | |
| | | 1603 | | { |
| | 0 | 1604 | | await _orderServices.ConfirmAccepted(id); |
| | | 1605 | | |
| | 0 | 1606 | | await _cache.UpdateCacheIncrementally(id); |
| | | 1607 | | } |
| | | 1608 | | |
| | | 1609 | | else |
| | | 1610 | | |
| | | 1611 | | { |
| | 0 | 1612 | | int[] idArray = ids.Split(',').Select(int.Parse).ToArray(); |
| | | 1613 | | |
| | 0 | 1614 | | foreach (var concretId in idArray) |
| | | 1615 | | |
| | | 1616 | | { |
| | 0 | 1617 | | await _orderServices.ConfirmAccepted(concretId); |
| | | 1618 | | |
| | 0 | 1619 | | await _cache.UpdateCacheIncrementally(concretId); |
| | | 1620 | | } |
| | | 1621 | | |
| | | 1622 | | |
| | 0 | 1623 | | if (Request.Cookies["selectedIds"] != null) |
| | | 1624 | | |
| | | 1625 | | { |
| | 0 | 1626 | | Response.Cookies.Delete("selectedIds"); |
| | | 1627 | | } |
| | | 1628 | | } |
| | | 1629 | | |
| | | 1630 | | |
| | 0 | 1631 | | return RedirectToAction(nameof(Index), new { sortOrder = GetSortStateCookie(), page = page }); |
| | 0 | 1632 | | } |
| | | 1633 | | |
| | | 1634 | | |
| | | 1635 | | [HttpPost] |
| | | 1636 | | [ValidateAntiForgeryToken] |
| | | 1637 | | public async Task<IActionResult> SaveSelectedStockListToSession([FromBody] List<StockItem> stockItems) |
| | | 1638 | | |
| | | 1639 | | { |
| | | 1640 | | try |
| | | 1641 | | |
| | | 1642 | | { |
| | 0 | 1643 | | var failedOrderIds = await _orderCartServices.CreateCartItem(stockItems); |
| | | 1644 | | |
| | 0 | 1645 | | await _cartCache.Update(); |
| | | 1646 | | |
| | 0 | 1647 | | await NotificationService.NotifyAllAsync("Заказы добавлены в корзину."); |
| | | 1648 | | |
| | 0 | 1649 | | return Json(new { success = true, failedOrderIds = failedOrderIds }); |
| | | 1650 | | } |
| | | 1651 | | |
| | 0 | 1652 | | catch (Exception e) |
| | | 1653 | | |
| | | 1654 | | { |
| | 0 | 1655 | | TempData["ErorrResult"] = "Ошибка при разборе списка корзины."; |
| | | 1656 | | |
| | 0 | 1657 | | await NotificationService.NotifyAllAsync($"Ошибка при разборе списка корзины. {e.Message}"); |
| | | 1658 | | |
| | 0 | 1659 | | return Json(new { success = false, message = "Ошибка на сервере" }); |
| | | 1660 | | } |
| | 0 | 1661 | | } |
| | | 1662 | | |
| | | 1663 | | |
| | | 1664 | | // Methods moved to OrderDetailsController: |
| | | 1665 | | // OrderDetailedInformation, OrderDetailedInformationForBitrix, OrderSubstitute, OrderStocks |
| | | 1666 | | |
| | | 1667 | | |
| | | 1668 | | |
| | | 1669 | | |
| | | 1670 | | [ServiceEndpoint] |
| | | 1671 | | [HttpPost] |
| | | 1672 | | public async Task<IActionResult> SplitOrders(string ids, string splitOption, bool onlyInSystem = false) |
| | | 1673 | | |
| | | 1674 | | { |
| | | 1675 | | try |
| | | 1676 | | |
| | | 1677 | | { |
| | 0 | 1678 | | var splitConfig = OzonOrderSplitConfig.FromRequest(splitOption, onlyInSystem); |
| | 0 | 1679 | | if (string.IsNullOrEmpty(splitConfig.SplitOption)) |
| | | 1680 | | |
| | | 1681 | | { |
| | 0 | 1682 | | return Json(new { success = false, message = "Не указан параметр разделения" }); |
| | | 1683 | | } |
| | | 1684 | | |
| | 0 | 1685 | | int[] idArray = ids.Split(',').Select(int.Parse).ToArray(); |
| | | 1686 | | |
| | | 1687 | | int part1; |
| | | 1688 | | int part2; |
| | | 1689 | | try |
| | | 1690 | | { |
| | 0 | 1691 | | (part1, part2) = splitConfig.ParseParts(); |
| | 0 | 1692 | | } |
| | 0 | 1693 | | catch (ArgumentException) |
| | | 1694 | | { |
| | 0 | 1695 | | return Json(new { success = false, message = "Неверный формат параметра разделения" }); |
| | | 1696 | | } |
| | | 1697 | | |
| | | 1698 | | |
| | 0 | 1699 | | var anyOzonSplit = false; |
| | 0 | 1700 | | var anyOzonQuantityAdjusted = false; |
| | 0 | 1701 | | var splitResults = new List<object>(); |
| | 0 | 1702 | | foreach (var id in idArray) |
| | | 1703 | | |
| | | 1704 | | { |
| | 0 | 1705 | | var (_, wasOzonSplit, wasOzonQuantityAdjusted, splitParts) = |
| | 0 | 1706 | | await PerformSplitOrderAsync(id, part1, part2, splitConfig.OnlyInSystem); |
| | 0 | 1707 | | anyOzonSplit = anyOzonSplit || wasOzonSplit; |
| | 0 | 1708 | | anyOzonQuantityAdjusted = anyOzonQuantityAdjusted || wasOzonQuantityAdjusted; |
| | 0 | 1709 | | splitResults.Add(new |
| | 0 | 1710 | | { |
| | 0 | 1711 | | originalOrderId = splitParts.OriginalOrderId, |
| | 0 | 1712 | | orderIds = splitParts.OrderIds, |
| | 0 | 1713 | | shipmentNumbers = splitParts.ShipmentNumbers, |
| | 0 | 1714 | | isOzonSplit = splitParts.IsOzonSplit |
| | 0 | 1715 | | }); |
| | | 1716 | | } |
| | | 1717 | | |
| | | 1718 | | |
| | 0 | 1719 | | await _cache.Update(); |
| | | 1720 | | |
| | 0 | 1721 | | var message = anyOzonSplit |
| | 0 | 1722 | | ? "Заказы успешно разделены на Ozon. Номера отправлений обновлены из ответа API." |
| | 0 | 1723 | | : anyOzonQuantityAdjusted |
| | 0 | 1724 | | ? "Заказы разделены локально: количество приведено к данным Ozon (в Ozon меньше, чем в системе). |
| | 0 | 1725 | | : $"Заказы успешно разделены ({part1}/{part2})"; |
| | | 1726 | | |
| | 0 | 1727 | | return Json(new |
| | 0 | 1728 | | |
| | 0 | 1729 | | { |
| | 0 | 1730 | | success = true, |
| | 0 | 1731 | | |
| | 0 | 1732 | | message = message, |
| | 0 | 1733 | | |
| | 0 | 1734 | | splitCount = idArray.Length, |
| | 0 | 1735 | | |
| | 0 | 1736 | | isOzonSplit = anyOzonSplit, |
| | 0 | 1737 | | |
| | 0 | 1738 | | splits = splitResults |
| | 0 | 1739 | | }); |
| | | 1740 | | } |
| | | 1741 | | |
| | 0 | 1742 | | catch (Exception ex) |
| | | 1743 | | { |
| | 0 | 1744 | | return Json(new |
| | 0 | 1745 | | |
| | 0 | 1746 | | { |
| | 0 | 1747 | | success = false, |
| | 0 | 1748 | | |
| | 0 | 1749 | | message = GetFriendlySplitErrorMessage(ex) |
| | 0 | 1750 | | }); |
| | | 1751 | | } |
| | 0 | 1752 | | } |
| | | 1753 | | |
| | | 1754 | | |
| | | 1755 | | [Authorize(Roles = "Admin")] |
| | | 1756 | | public IActionResult DeleteDuplicateOrders() |
| | | 1757 | | |
| | | 1758 | | { |
| | | 1759 | | int? duplicateCount; |
| | | 1760 | | |
| | | 1761 | | int? deletedRowsCount; |
| | | 1762 | | |
| | | 1763 | | |
| | 0 | 1764 | | (duplicateCount, deletedRowsCount) = _duplicateOrdersServices.DeleteDuplicateOrders(); |
| | | 1765 | | |
| | 0 | 1766 | | ClearSelectedIdsSession(); |
| | | 1767 | | |
| | 0 | 1768 | | return RedirectToAction(nameof(System.Index)); |
| | | 1769 | | } |
| | | 1770 | | |
| | | 1771 | | |
| | | 1772 | | private async Task<bool> OrderExists(int id) |
| | | 1773 | | |
| | | 1774 | | { |
| | 0 | 1775 | | return await _orderServices.GetOrder(id) != null; |
| | 0 | 1776 | | } |
| | | 1777 | | |
| | | 1778 | | |
| | | 1779 | | public void SetSortOrderViewData(OrderSortState sortOrder) |
| | | 1780 | | { |
| | 0 | 1781 | | var sortData = _dataFilterManager.GetSortOrderViewData(sortOrder); |
| | 0 | 1782 | | foreach (var item in sortData) |
| | | 1783 | | { |
| | 0 | 1784 | | ViewData[item.Key] = item.Value; |
| | | 1785 | | } |
| | | 1786 | | |
| | | 1787 | | // Передаем текущий sortOrder для отображения стрелки только на активном столбце |
| | 0 | 1788 | | ViewData["CurrentSortOrder"] = sortOrder; |
| | 0 | 1789 | | } |
| | | 1790 | | |
| | | 1791 | | |
| | | 1792 | | public IEnumerable<Order> ApplySortOrder(IEnumerable<Order> orders, OrderSortState sortOrder) |
| | | 1793 | | { |
| | 0 | 1794 | | return _dataFilterManager.ApplySortOrder(orders, sortOrder); |
| | | 1795 | | } |
| | | 1796 | | |
| | | 1797 | | |
| | | 1798 | | private async Task<OrdersIndexQueryResult> LoadOrdersIndexPageAsync( |
| | | 1799 | | OrderFilterModel filterData, |
| | | 1800 | | int page, |
| | | 1801 | | int pageSize, |
| | | 1802 | | OrderSortState sortOrder, |
| | | 1803 | | AccessProfile? accessProfile, |
| | | 1804 | | bool hasFilters, |
| | | 1805 | | bool hasUserAccessRestrictions, |
| | | 1806 | | bool isReturnsListPage = false) |
| | | 1807 | | { |
| | 0 | 1808 | | return await _ordersIndexQueryService.LoadPageAsync(new OrdersIndexQueryRequest |
| | 0 | 1809 | | { |
| | 0 | 1810 | | Filter = filterData, |
| | 0 | 1811 | | Page = page, |
| | 0 | 1812 | | PageSize = pageSize, |
| | 0 | 1813 | | SortOrder = sortOrder, |
| | 0 | 1814 | | AccessProfile = accessProfile, |
| | 0 | 1815 | | HasFilters = hasFilters, |
| | 0 | 1816 | | HasUserAccessRestrictions = hasUserAccessRestrictions, |
| | 0 | 1817 | | IsReturnsListPage = isReturnsListPage, |
| | 0 | 1818 | | UserId = User?.FindFirstValue(ClaimTypes.NameIdentifier), |
| | 0 | 1819 | | CancellationToken = HttpContext.RequestAborted |
| | 0 | 1820 | | }); |
| | 0 | 1821 | | } |
| | | 1822 | | |
| | | 1823 | | private (List<Order> distinctOrders, List<Order> ordersForPage) ShapeOrdersAfterLoad( |
| | | 1824 | | List<Order> ordersFromCache, |
| | | 1825 | | bool requiresInMemorySort, |
| | | 1826 | | OrderSortState sortOrder, |
| | | 1827 | | OrderFilterModel filterData, |
| | | 1828 | | int pageSize) |
| | | 1829 | | { |
| | 0 | 1830 | | if (requiresInMemorySort) |
| | | 1831 | | { |
| | 0 | 1832 | | ordersFromCache = ApplySortOrder(ordersFromCache, sortOrder).ToList(); |
| | | 1833 | | } |
| | | 1834 | | |
| | 0 | 1835 | | var distinctOrders = _ordersIndexQueryService.PrepareDistinctOrders( |
| | 0 | 1836 | | ordersFromCache, |
| | 0 | 1837 | | filterData.GroupByShipment); |
| | 0 | 1838 | | distinctOrders = _ordersIndexQueryService.SelectOrdersForPage( |
| | 0 | 1839 | | distinctOrders, 1, pageSize, out var ordersForPage); |
| | 0 | 1840 | | return (distinctOrders, ordersForPage); |
| | | 1841 | | } |
| | | 1842 | | |
| | | 1843 | | |
| | | 1844 | | private async Task ApplyOrdersIndexPageViewDataAsync( |
| | | 1845 | | string userId, |
| | | 1846 | | bool isAdmin, |
| | | 1847 | | CancellationToken ct, |
| | | 1848 | | Services.Authorization.Dtos.UserPermissionsBundle? prefetchedBundle = null) |
| | | 1849 | | { |
| | 0 | 1850 | | var data = await _ordersIndexPageViewDataService.BuildAsync(new OrdersIndexPageViewDataRequest |
| | 0 | 1851 | | { |
| | 0 | 1852 | | UserId = userId, |
| | 0 | 1853 | | IsWebAdmin = isAdmin, |
| | 0 | 1854 | | PrefetchedPermissionBundle = prefetchedBundle, |
| | 0 | 1855 | | CancellationToken = ct |
| | 0 | 1856 | | }); |
| | 0 | 1857 | | OrdersIndexPageViewDataApplicator.Apply(data, ViewBag); |
| | 0 | 1858 | | } |
| | | 1859 | | |
| | | 1860 | | |
| | | 1861 | | private async Task ApplyFilterListsToViewAsync( |
| | | 1862 | | List<Order>? filteredData, |
| | | 1863 | | AccessProfile? accessProfile, |
| | | 1864 | | bool useFilteredData) |
| | | 1865 | | { |
| | 0 | 1866 | | var userId = User?.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 1867 | | var scopeExpr = _userScopeProvider.GetFilterExpression("Order"); |
| | | 1868 | | |
| | 0 | 1869 | | var data = await _orderFilterListsService.BuildAsync( |
| | 0 | 1870 | | new OrderFilterListsBuildRequest |
| | 0 | 1871 | | { |
| | 0 | 1872 | | FilteredData = filteredData, |
| | 0 | 1873 | | AccessProfile = accessProfile, |
| | 0 | 1874 | | UseFilteredData = useFilteredData, |
| | 0 | 1875 | | UserId = userId, |
| | 0 | 1876 | | OrderScopeExpression = scopeExpr |
| | 0 | 1877 | | }, |
| | 0 | 1878 | | HttpContext.RequestAborted); |
| | | 1879 | | |
| | 0 | 1880 | | OrderFilterListsViewDataApplicator.Apply(data, ViewBag); |
| | 0 | 1881 | | } |
| | | 1882 | | |
| | | 1883 | | |
| | | 1884 | | public async Task SetFilterLists(List<Order> filteredData, AccessProfile? accessProfile = null, |
| | | 1885 | | bool useFilteredData = false) |
| | | 1886 | | { |
| | 0 | 1887 | | await ApplyFilterListsToViewAsync( |
| | 0 | 1888 | | useFilteredData ? filteredData : null, |
| | 0 | 1889 | | accessProfile, |
| | 0 | 1890 | | useFilteredData); |
| | 0 | 1891 | | } |
| | | 1892 | | |
| | | 1893 | | private async Task<IQueryable<Order>> ApplyOrderDataScopeAsync(IQueryable<Order> ordersQuery) |
| | | 1894 | | { |
| | 0 | 1895 | | var userId = User?.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 1896 | | return await _dataScopeApplier.ApplyAsync(ordersQuery, userId, HttpContext.RequestAborted); |
| | 0 | 1897 | | } |
| | | 1898 | | |
| | | 1899 | | private async Task<int[]> FilterOrderIdsByDataScopeAsync(IEnumerable<int> ids) |
| | | 1900 | | { |
| | 0 | 1901 | | var userId = User?.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 1902 | | return await _dataScopeIdFilterService.FilterOrderIdsAsync( |
| | 0 | 1903 | | userId, ids, HttpContext.RequestAborted); |
| | 0 | 1904 | | } |
| | | 1905 | | |
| | | 1906 | | private async Task<List<T>> FilterByOrderScopeIdsAsync<T>( |
| | | 1907 | | IEnumerable<T> source, |
| | | 1908 | | Func<T, int> idSelector, |
| | | 1909 | | string scopeFieldName) |
| | | 1910 | | { |
| | 0 | 1911 | | var userId = User?.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 1912 | | return await _dataScopeIdFilterService.FilterItemsByScopeFieldAsync( |
| | 0 | 1913 | | userId, source, idSelector, scopeFieldName, HttpContext.RequestAborted); |
| | 0 | 1914 | | } |
| | | 1915 | | |
| | | 1916 | | private static void EnsureOrderColumnsVisibilityProfile(CustomIdentityUser? user) |
| | | 1917 | | { |
| | 0 | 1918 | | if (user == null) |
| | | 1919 | | { |
| | 0 | 1920 | | return; |
| | | 1921 | | } |
| | | 1922 | | |
| | 0 | 1923 | | if (user.AccessProfileId != null && user.AccessProfile?.AvailableOrderColumns?.Any() == true) |
| | | 1924 | | { |
| | 0 | 1925 | | return; |
| | | 1926 | | } |
| | | 1927 | | |
| | 0 | 1928 | | user.AccessProfileId ??= -1; |
| | 0 | 1929 | | user.AccessProfile ??= new AccessProfile(); |
| | 0 | 1930 | | user.AccessProfile.AvailableOrderColumns = OrderListColumnCatalog.All |
| | 0 | 1931 | | .Select(c => c.LegacyAccessKey) |
| | 0 | 1932 | | .Where(k => !string.IsNullOrWhiteSpace(k)) |
| | 0 | 1933 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 1934 | | .ToList()!; |
| | 0 | 1935 | | } |
| | | 1936 | | |
| | | 1937 | | private static void NormalizeSyntheticAccessProfile(CustomIdentityUser? user) |
| | | 1938 | | { |
| | 0 | 1939 | | if (user?.AccessProfileId is <= 0) |
| | | 1940 | | { |
| | 0 | 1941 | | user.AccessProfileId = null; |
| | | 1942 | | } |
| | 0 | 1943 | | } |
| | | 1944 | | |
| | | 1945 | | public void SaveSortStateCookie(OrderSortState sortOrder) |
| | | 1946 | | |
| | | 1947 | | { |
| | 0 | 1948 | | SaveSortStateCookie(sortOrder, "SortState"); |
| | 0 | 1949 | | } |
| | | 1950 | | |
| | | 1951 | | public void SaveSortStateCookie(OrderSortState sortOrder, string cookieKey) |
| | | 1952 | | |
| | | 1953 | | { |
| | 0 | 1954 | | if (sortOrder != OrderSortState.StandardState) |
| | | 1955 | | |
| | | 1956 | | { |
| | 0 | 1957 | | Response.Cookies.Delete(cookieKey); |
| | | 1958 | | |
| | 0 | 1959 | | Response.Cookies.Append(cookieKey, sortOrder.ToString()); |
| | | 1960 | | } |
| | 0 | 1961 | | } |
| | | 1962 | | |
| | | 1963 | | |
| | | 1964 | | private OrderSortState GetSortStateCookie() |
| | | 1965 | | |
| | | 1966 | | { |
| | 0 | 1967 | | return GetSortStateCookie("SortState"); |
| | | 1968 | | } |
| | | 1969 | | |
| | | 1970 | | private OrderSortState GetSortStateCookie(string cookieKey) |
| | | 1971 | | |
| | | 1972 | | { |
| | 0 | 1973 | | var sortStateCookie = Request.Cookies[cookieKey]; |
| | | 1974 | | |
| | 0 | 1975 | | if (!string.IsNullOrEmpty(sortStateCookie) && |
| | 0 | 1976 | | Enum.TryParse<OrderSortState>(sortStateCookie, out var savedSortState)) |
| | | 1977 | | |
| | | 1978 | | { |
| | 0 | 1979 | | return savedSortState; |
| | | 1980 | | } |
| | | 1981 | | |
| | | 1982 | | |
| | 0 | 1983 | | return OrderSortState.StandardState; |
| | | 1984 | | } |
| | | 1985 | | |
| | | 1986 | | |
| | | 1987 | | private void SetInfoMessage() |
| | | 1988 | | |
| | | 1989 | | { |
| | 0 | 1990 | | if (TempData.ContainsKey("UploadResult") && TempData["UploadResult"] != null) |
| | | 1991 | | |
| | | 1992 | | { |
| | 0 | 1993 | | int[] result = TempData["UploadResult"] as int[] ?? []; |
| | | 1994 | | |
| | 0 | 1995 | | string period = TempData["UploadResultPeriod"]?.ToString() ?? string.Empty; |
| | | 1996 | | |
| | 0 | 1997 | | ViewData["UploadResult"] = result; |
| | | 1998 | | |
| | 0 | 1999 | | ViewData["UploadResultPeriod"] = period; |
| | | 2000 | | } |
| | | 2001 | | |
| | | 2002 | | |
| | 0 | 2003 | | if (TempData.ContainsKey("TransactionResult") && TempData["TransactionResult"] != null) |
| | | 2004 | | |
| | | 2005 | | { |
| | 0 | 2006 | | string result = TempData["TransactionResult"]?.ToString() ?? string.Empty; |
| | | 2007 | | |
| | 0 | 2008 | | ViewData["TransactionResult"] = result; |
| | | 2009 | | } |
| | | 2010 | | |
| | | 2011 | | |
| | 0 | 2012 | | if (TempData.ContainsKey("ErorrResult") && TempData["ErorrResult"] != null) |
| | | 2013 | | |
| | | 2014 | | { |
| | 0 | 2015 | | string result = TempData["ErorrResult"]?.ToString() ?? string.Empty; |
| | | 2016 | | |
| | 0 | 2017 | | ViewData["ErorrResult"] = result; |
| | | 2018 | | } |
| | | 2019 | | |
| | 0 | 2020 | | if (TempData.ContainsKey("TransactionErrorCode") && TempData["TransactionErrorCode"] != null) |
| | | 2021 | | { |
| | 0 | 2022 | | ViewData["TransactionErrorCode"] = TempData["TransactionErrorCode"]?.ToString(); |
| | | 2023 | | } |
| | | 2024 | | |
| | | 2025 | | |
| | 0 | 2026 | | if (TempData.ContainsKey("OrdersNotFoundInOzone") && TempData["OrdersNotFoundInOzone"] != null) |
| | | 2027 | | |
| | | 2028 | | { |
| | 0 | 2029 | | string result = TempData["OrdersNotFoundInOzone"]?.ToString() ?? string.Empty; |
| | | 2030 | | |
| | 0 | 2031 | | ViewData["OrdersNotFoundInOzone"] = result; |
| | | 2032 | | } |
| | | 2033 | | |
| | | 2034 | | |
| | 0 | 2035 | | if (TempData.ContainsKey("SearchByBarcode") && TempData["SearchByBarcode"] is true) |
| | | 2036 | | |
| | | 2037 | | { |
| | 0 | 2038 | | ViewData["SearchByBarcode"] = true; |
| | | 2039 | | |
| | 0 | 2040 | | ViewData["BarcodeValue"] = TempData["BarcodeValue"]?.ToString(); |
| | | 2041 | | |
| | 0 | 2042 | | ViewData["FoundOrdersCount"] = TempData["FoundOrdersCount"]?.ToString(); |
| | | 2043 | | } |
| | 0 | 2044 | | } |
| | | 2045 | | |
| | | 2046 | | |
| | | 2047 | | private List<int> RetrieveSelectedIdsFromSession() |
| | | 2048 | | { |
| | 0 | 2049 | | var selectedIds = HttpContext.Session.GetString("selectedIds"); |
| | 0 | 2050 | | if (string.IsNullOrEmpty(selectedIds)) |
| | 0 | 2051 | | return new List<int>(); |
| | 0 | 2052 | | return JsonConvert.DeserializeObject<List<int>>(selectedIds) ?? new List<int>(); |
| | | 2053 | | } |
| | | 2054 | | |
| | | 2055 | | private void ClearSelectedIdsSession() |
| | | 2056 | | { |
| | 0 | 2057 | | HttpContext.Session.SetString("selectedIds", JsonConvert.SerializeObject(new List<int>())); |
| | 0 | 2058 | | } |
| | | 2059 | | |
| | | 2060 | | |
| | | 2061 | | /// <summary> |
| | | 2062 | | /// Обновляет кэш для указанной этикетки |
| | | 2063 | | /// </summary> |
| | | 2064 | | private void UpdateLabelCache(string shipmentNumber, bool exists) => |
| | 0 | 2065 | | _labelExistenceService.SetShipmentExists(shipmentNumber, exists); |
| | | 2066 | | |
| | | 2067 | | |
| | | 2068 | | [HttpGet] |
| | | 2069 | | // Methods moved to OrderLookupController: |
| | | 2070 | | // GetClientStatusesByClient, GetClientStatusesByClientType, GetCurrencyByCode, |
| | | 2071 | | // SearchEtProducers, GetEtProducerMarketPrefix, GetEtProducersByArticle, |
| | | 2072 | | // CheckOrderUnique, GetProductByArticle, SearchArticleByEAN |
| | | 2073 | | |
| | | 2074 | | /// <summary> |
| | | 2075 | | /// Возвращает все заказы с указанным ProductKey для модального окна. |
| | | 2076 | | /// </summary> |
| | | 2077 | | [HttpGet] |
| | | 2078 | | public async Task<IActionResult> GetOrdersByProductKey(string key, bool includeArchived = false) |
| | | 2079 | | { |
| | 0 | 2080 | | if (string.IsNullOrEmpty(key)) return Json(Array.Empty<object>()); |
| | | 2081 | | |
| | 0 | 2082 | | var query = _orderServices.GetOrdersQueryable(includeArchived) |
| | 0 | 2083 | | .Where(o => o.ProductKey == key); |
| | | 2084 | | |
| | 0 | 2085 | | query = await ApplyOrderDataScopeAsync(query); |
| | | 2086 | | |
| | 0 | 2087 | | var orders = await query |
| | 0 | 2088 | | .Select(o => new |
| | 0 | 2089 | | { |
| | 0 | 2090 | | o.Id, |
| | 0 | 2091 | | o.ShipmentNumber, |
| | 0 | 2092 | | ProcessingDate = o.ProcessingDate != null |
| | 0 | 2093 | | ? o.ProcessingDate.Value.ToString("dd.MM.yyyy") |
| | 0 | 2094 | | : "", |
| | 0 | 2095 | | Status = o.Status ?? "", |
| | 0 | 2096 | | o.Article, |
| | 0 | 2097 | | o.ProductName, |
| | 0 | 2098 | | Price = o.Price ?? 0m |
| | 0 | 2099 | | }) |
| | 0 | 2100 | | .OrderByDescending(o => o.ProcessingDate) |
| | 0 | 2101 | | .Take(500) |
| | 0 | 2102 | | .ToListAsync(); |
| | | 2103 | | |
| | 0 | 2104 | | return Json(orders); |
| | 0 | 2105 | | } |
| | | 2106 | | } |
| | | 2107 | | } |