| | | 1 | | using Microsoft.AspNetCore.Mvc; |
| | | 2 | | using OzonDomains; |
| | | 3 | | using OzonDomains.Models; |
| | | 4 | | using OzonOrdersWeb.Areas.Studio2.Controllers.Base; |
| | | 5 | | using OzonOrdersWeb.Areas.Studio2.Models.Transactions; |
| | | 6 | | using OzonRepositories.Context; |
| | | 7 | | using Services.BackgroundJobsServices; |
| | | 8 | | using Services.ApiServices; |
| | | 9 | | using Services.ApiServices._1CApi; |
| | | 10 | | using Services.ApiServices.OzonApi; |
| | | 11 | | using Services.Authorization.Services; |
| | | 12 | | using Services.CacheServices.Cache.OzonOrdersCache; |
| | | 13 | | using Services.CacheServices.Cache.UserCacheService; |
| | | 14 | | using Services.DataServices; |
| | | 15 | | using OzonOrdersWeb.WebServices.Currency; |
| | | 16 | | using Services.TransactionUtilsServices; |
| | | 17 | | using Services.CacheServices.Cache; |
| | | 18 | | |
| | | 19 | | namespace OzonOrdersWeb.Areas.Studio2.Controllers.Transactions; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Контроллер транзакции "Возвращено поставщику" |
| | | 23 | | /// </summary> |
| | | 24 | | public class ReturnToSupplierTransactionController : BaseTransactionController |
| | | 25 | | { |
| | | 26 | | private readonly WarehouseSelectionResolver _warehouseSelectionResolver; |
| | | 27 | | private readonly OneCReceiptWarehouseHistoryResolver _receiptWarehouseHistoryResolver; |
| | | 28 | | |
| | | 29 | | public ReturnToSupplierTransactionController( |
| | | 30 | | ApplicationDbContext context, |
| | | 31 | | AppStatusDataServices appStatusServices, |
| | | 32 | | OrdersDataServices orderServices, |
| | | 33 | | TransactionManager transactionManager, |
| | | 34 | | TransactionCache transactionCache, |
| | | 35 | | SupplierDataServices supplierDataServices, |
| | | 36 | | IUserCacheService userCacheService, |
| | | 37 | | ICurrencyRatesViewBagService currencyRatesViewBagService, |
| | | 38 | | CacheUpdater<Order> cacheUpdater, |
| | | 39 | | OrderCache orderCache, |
| | | 40 | | WarehouseDataServices warehouseDataServices, |
| | | 41 | | ExpenseTypeDataServices expenseTypeDataServices, |
| | | 42 | | OrderExtraExpenseDataServices orderExtraExpenseDataServices, |
| | | 43 | | OneCDataManager oneCDataManager, |
| | | 44 | | OneCTransferManager oneCTransferManager, |
| | | 45 | | StatusTransitionDataServices statusTransitionDataServices, |
| | | 46 | | IScopeFilterValuesService scopeFilterValuesService, |
| | | 47 | | WarehouseSelectionResolver warehouseSelectionResolver, |
| | | 48 | | OneCReceiptWarehouseHistoryResolver receiptWarehouseHistoryResolver, |
| | | 49 | | OzonOrderCancellationService? ozonCancellationService = null) |
| | 0 | 50 | | : base(context, appStatusServices, orderServices, transactionManager, transactionCache, |
| | 0 | 51 | | supplierDataServices, userCacheService, currencyRatesViewBagService, cacheUpdater, orderCache, |
| | 0 | 52 | | oneCDataManager, warehouseDataServices, bitrixStockRepository: null, proxyHttpClientService: null, |
| | 0 | 53 | | oneCTransferManager, orderCartServices: null, warehouseMappingDataServices: null, |
| | 0 | 54 | | expenseTypeDataServices, orderExtraExpenseDataServices, statusTransitionDataServices, |
| | 0 | 55 | | scopeFilterValuesService, ozonCancellationService: ozonCancellationService) |
| | | 56 | | { |
| | 0 | 57 | | _warehouseSelectionResolver = warehouseSelectionResolver; |
| | 0 | 58 | | _receiptWarehouseHistoryResolver = receiptWarehouseHistoryResolver; |
| | 0 | 59 | | } |
| | | 60 | | |
| | 0 | 61 | | protected override TransactionConfig GetTransactionConfig() => new() |
| | 0 | 62 | | { |
| | 0 | 63 | | TransactionType = TransactionType.ReturnToSupplier, |
| | 0 | 64 | | PrimaryStatusName = "Возвращено поставщику", |
| | 0 | 65 | | ViewName = "CreateReturnToSupplierTransaction", |
| | 0 | 66 | | RequiredSourceStatuses = new List<string> { "Заказан поставщику", "ПринятНаСкладе", "Возврат поставщику", "Возвр |
| | 0 | 67 | | IncludeCancelledOrders = true, |
| | 0 | 68 | | SupportsOzonCancelPanel = true, |
| | 0 | 69 | | LoadWarehouseListForSelector = true, |
| | 0 | 70 | | UseCustomWarehousesFor1C = true, |
| | 0 | 71 | | CheckStockBefore1C = true, |
| | 0 | 72 | | CreateTransactionMethod = (tm, orders, userName, createAt, comment) => |
| | 0 | 73 | | tm.CreateReturnToSupplierTransaction(orders, userName, createAt, comment) |
| | 0 | 74 | | }; |
| | | 75 | | |
| | | 76 | | public async Task<IActionResult> CreateReturnToSupplierTransaction(string ids, int page) |
| | | 77 | | { |
| | 0 | 78 | | var result = await CreateTransactionBase(ids, page); |
| | 0 | 79 | | if (result is not ViewResult { Model: OzonOrdersWeb.ViewModels.OrderViewModels.MultiplayEditOrderViewModel viewM |
| | 0 | 80 | | viewModel.Orders.Count == 0) |
| | | 81 | | { |
| | 0 | 82 | | return result; |
| | | 83 | | } |
| | | 84 | | |
| | 0 | 85 | | var senderResolution = await _warehouseSelectionResolver |
| | 0 | 86 | | .ResolveCustomerReturnRecipientByOrderAsync(viewModel.Orders); |
| | | 87 | | |
| | | 88 | | // Ошибка автоподстановки не блокирует ручной выбор: пользователь может указать склад сам. |
| | 0 | 89 | | if (senderResolution.HasBlockingErrors) |
| | 0 | 90 | | ViewData["ReturnSupplierSenderRuleInfo"] = string.Join(" ", senderResolution.BlockingErrors); |
| | | 91 | | |
| | 0 | 92 | | ViewData["ReturnSupplierSenderByOrder"] = senderResolution.RecipientByOrderId; |
| | 0 | 93 | | ViewData["ReturnSupplierSenderExplanationByOrder"] = senderResolution.RecipientExplanationByOrderId; |
| | 0 | 94 | | ViewData["ReturnSupplierSenderReturnWarehouseOrderIds"] = senderResolution.ReturnWarehouseOrderIds; |
| | 0 | 95 | | ViewData["ReturnSupplierZasylOptionsByOrderId"] = await _warehouseSelectionResolver |
| | 0 | 96 | | .BuildCustomerReturnZasylOptionsAsync(viewModel.Orders, viewModel.Warehouses.Select(warehouse => warehouse.N |
| | | 97 | | |
| | 0 | 98 | | var receiptHistoryByArticle = await _receiptWarehouseHistoryResolver.ResolveByArticlesAsync( |
| | 0 | 99 | | viewModel.Orders.Select(order => order.Article), |
| | 0 | 100 | | viewModel.Warehouses.Select(warehouse => warehouse.Name)); |
| | 0 | 101 | | var recipientHistoryByOrder = new Dictionary<int, IReadOnlyList<OneCReceiptWarehouseSuggestion>>(); |
| | 0 | 102 | | var recipientByOrder = new Dictionary<int, string>(); |
| | 0 | 103 | | var recipientExplanationByOrder = new Dictionary<int, string>(); |
| | | 104 | | |
| | 0 | 105 | | foreach (var order in viewModel.Orders) |
| | | 106 | | { |
| | 0 | 107 | | var article = order.Article?.Trim(); |
| | 0 | 108 | | var history = !string.IsNullOrWhiteSpace(article) && receiptHistoryByArticle.TryGetValue(article, out var fo |
| | 0 | 109 | | ? foundHistory |
| | 0 | 110 | | : []; |
| | 0 | 111 | | recipientHistoryByOrder[order.Id] = history; |
| | | 112 | | |
| | 0 | 113 | | if (history.FirstOrDefault() is { } latestReceipt) |
| | | 114 | | { |
| | 0 | 115 | | recipientByOrder[order.Id] = latestReceipt.Warehouse; |
| | 0 | 116 | | recipientExplanationByOrder[order.Id] = |
| | 0 | 117 | | $"Последний проведённый приход: {latestReceipt.Warehouse}, {latestReceipt.Date:dd.MM.yyyy}, №{latest |
| | | 118 | | } |
| | | 119 | | else |
| | | 120 | | { |
| | 0 | 121 | | recipientExplanationByOrder[order.Id] = |
| | 0 | 122 | | "Проведённых приходов по товару на доступные склады 1С не найдено — выберите склад получателя вручну |
| | | 123 | | } |
| | | 124 | | } |
| | | 125 | | |
| | 0 | 126 | | ViewData["ReturnSupplierRecipientByOrder"] = recipientByOrder; |
| | 0 | 127 | | ViewData["ReturnSupplierRecipientHistoryByOrder"] = recipientHistoryByOrder; |
| | 0 | 128 | | ViewData["ReturnSupplierRecipientExplanationByOrder"] = recipientExplanationByOrder; |
| | 0 | 129 | | return result; |
| | 0 | 130 | | } |
| | | 131 | | |
| | | 132 | | [HttpPost] |
| | | 133 | | [ValidateAntiForgeryToken] |
| | | 134 | | public Task<IActionResult> CreateReturnToSupplierTransaction( |
| | | 135 | | List<Order> orders, |
| | | 136 | | string userName, |
| | | 137 | | string? comment, |
| | | 138 | | int page, |
| | | 139 | | string? deletedOrders, |
| | | 140 | | Dictionary<int, string?>? orderSupplierMap, |
| | | 141 | | bool processIn1C = false, |
| | | 142 | | string? warehouseSender = null, |
| | | 143 | | string? warehouseRecipient = null, |
| | | 144 | | Dictionary<int, string>? senderWarehouseByOrder = null, |
| | | 145 | | Dictionary<int, string>? recipientWarehouseByOrder = null) |
| | | 146 | | { |
| | 0 | 147 | | if (!processIn1C) |
| | 0 | 148 | | return CreateTransactionPostBase(orders, userName, comment, page, deletedOrders, orderSupplierMap); |
| | | 149 | | |
| | 0 | 150 | | return CreateReturnToSupplierTransactionWithWarehouseValidation( |
| | 0 | 151 | | orders, userName, comment, page, deletedOrders, orderSupplierMap, |
| | 0 | 152 | | senderWarehouseByOrder, recipientWarehouseByOrder); |
| | | 153 | | } |
| | | 154 | | |
| | | 155 | | private async Task<IActionResult> CreateReturnToSupplierTransactionWithWarehouseValidation( |
| | | 156 | | List<Order> orders, |
| | | 157 | | string userName, |
| | | 158 | | string? comment, |
| | | 159 | | int page, |
| | | 160 | | string? deletedOrders, |
| | | 161 | | Dictionary<int, string?>? orderSupplierMap, |
| | | 162 | | Dictionary<int, string>? senderWarehouseByOrder, |
| | | 163 | | Dictionary<int, string>? recipientWarehouseByOrder) |
| | | 164 | | { |
| | | 165 | | try |
| | | 166 | | { |
| | 0 | 167 | | var candidateOrders = orders ?? []; |
| | 0 | 168 | | if (!string.IsNullOrWhiteSpace(deletedOrders)) |
| | | 169 | | { |
| | 0 | 170 | | var deletedOrderIds = DeletedOrderIds.Parse(deletedOrders); |
| | 0 | 171 | | candidateOrders = candidateOrders.Where(o => !deletedOrderIds.Contains(o.Id)).ToList(); |
| | | 172 | | } |
| | | 173 | | |
| | 0 | 174 | | var oneCDataManager = OneCDataManager ?? throw new TransactionException( |
| | 0 | 175 | | TransactionErrorCode.OneCUnavailable, "Интеграция с 1С недоступна."); |
| | 0 | 176 | | var availableWarehouses = (await oneCDataManager.GetWarehouseListAsync()) |
| | 0 | 177 | | .Select(w => w.Name) |
| | 0 | 178 | | .Where(name => !string.IsNullOrWhiteSpace(name)) |
| | 0 | 179 | | .Select(name => name!) |
| | 0 | 180 | | .OrderBy(name => name) |
| | 0 | 181 | | .ToList(); |
| | 0 | 182 | | availableWarehouses = await FilterBitrixWarehouseNamesByScope(availableWarehouses); |
| | | 183 | | |
| | 0 | 184 | | var senders = senderWarehouseByOrder ?? []; |
| | 0 | 185 | | var recipients = recipientWarehouseByOrder ?? []; |
| | 0 | 186 | | var candidateOrderIds = candidateOrders.Select(o => o.Id).ToHashSet(); |
| | 0 | 187 | | if (senders.Keys.Any(id => !candidateOrderIds.Contains(id)) || |
| | 0 | 188 | | recipients.Keys.Any(id => !candidateOrderIds.Contains(id))) |
| | | 189 | | { |
| | 0 | 190 | | throw new TransactionException(TransactionErrorCode.OneCSenderWarehouseMissing, |
| | 0 | 191 | | "Переданы некорректные данные по маршрутам складов."); |
| | | 192 | | } |
| | | 193 | | |
| | 0 | 194 | | foreach (var order in candidateOrders) |
| | | 195 | | { |
| | 0 | 196 | | if (!senders.TryGetValue(order.Id, out var sender) || string.IsNullOrWhiteSpace(sender)) |
| | 0 | 197 | | throw new TransactionException(TransactionErrorCode.OneCSenderWarehouseMissing, |
| | 0 | 198 | | $"Не указан склад отправителя для заказа {order.ShipmentNumber}."); |
| | 0 | 199 | | if (!recipients.TryGetValue(order.Id, out var recipient) || string.IsNullOrWhiteSpace(recipient)) |
| | 0 | 200 | | throw new TransactionException(TransactionErrorCode.OneCRecipientWarehouseMissing, |
| | 0 | 201 | | $"Не указан склад получателя для заказа {order.ShipmentNumber}."); |
| | 0 | 202 | | if (!availableWarehouses.Contains(sender.Trim(), StringComparer.OrdinalIgnoreCase) || |
| | 0 | 203 | | !availableWarehouses.Contains(recipient.Trim(), StringComparer.OrdinalIgnoreCase)) |
| | | 204 | | { |
| | 0 | 205 | | throw new TransactionException(TransactionErrorCode.OneCSenderWarehouseMissing, |
| | 0 | 206 | | $"Склад маршрута для заказа {order.ShipmentNumber} недоступен в списке складов 1С или по текущим |
| | | 207 | | } |
| | 0 | 208 | | if (string.Equals(sender.Trim(), recipient.Trim(), StringComparison.OrdinalIgnoreCase)) |
| | 0 | 209 | | throw new TransactionException(TransactionErrorCode.OneCWarehousesMustDiffer, |
| | 0 | 210 | | $"Склад отправителя и получателя не могут совпадать (заказ {order.ShipmentNumber})."); |
| | | 211 | | } |
| | | 212 | | |
| | 0 | 213 | | var normalizedSenders = senders.ToDictionary(pair => pair.Key, pair => pair.Value.Trim()); |
| | 0 | 214 | | var normalizedRecipients = recipients.ToDictionary(pair => pair.Key, pair => pair.Value.Trim()); |
| | | 215 | | |
| | 0 | 216 | | return await CreateTransactionPostBase( |
| | 0 | 217 | | candidateOrders, userName, comment, page, string.Empty, orderSupplierMap, |
| | 0 | 218 | | processIn1C: true, |
| | 0 | 219 | | recipientWarehouseByOrder: normalizedRecipients, |
| | 0 | 220 | | senderWarehouseByOrder: normalizedSenders); |
| | | 221 | | } |
| | 0 | 222 | | catch (TransactionException ex) |
| | | 223 | | { |
| | 0 | 224 | | TempData["TransactionErrorCode"] = ex.Code.ToString(); |
| | 0 | 225 | | TempData["ErorrResult"] = ex.Message; |
| | 0 | 226 | | return Json(new { redirectTo = Url.Action("Index", "Orders", new { sortOrder = GetSortStateCookie(), page }) |
| | | 227 | | } |
| | 0 | 228 | | } |
| | | 229 | | } |